题解 | #创建单例对象#

创建单例对象

http://www.nowcoder.com/practice/9b316cd2d6264776918bc4bc31f37aec

按照题中要求,应该补充该类的getInstance()方法,由于Singleton类是单例的,每次调用该类的getInstance()方法都将得到相同的Singleton类型实例,所以getInstance()方法的返回类型应为Singleton。预设代码中,getInstance()方法为类直接调用,所以该方法应为静态方法,那么此处得知getInstance()方法的应为:

public static Singleton getInstance() {
    
}

在该方法中进行判断,若instance == null即不存在实例时则新建Singleton,否则直接返回已有的instance。将此处判断逻辑写入getInstance()方法中,补全getInstance()方法。这部分参考代码如下:

 public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    } 

附上完整代码:

public class Main {

    public static void main(String[] args) {
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        System.out.println(s1 == s2);
    }

}

class Singleton {

    private static Singleton instance;

    private Singleton() {

    }
public static Singleton getInstance() {
    if (instance == null) {
        instance = new Singleton();
    }
    return instance;
}
    //write your code here......


}
全部评论

相关推荐

迷茫的大四🐶:自信一点,我认为你可以拿到50k,低于50k完全配不上你的能力,兄弟,不要被他们骗了,你可以的
点赞 评论 收藏
分享
05-03 12:45
西南大学 Java
nsnzkv:你这项目写的内容太多了,说实话都是在给自己挖坑,就算简历过了,后面面试也难受
点赞 评论 收藏
分享
评论
39
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务