题解 | #创建单例对象#

创建单例对象

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......


}
全部评论

相关推荐

那一天的Java_Java起来:他本来公司就是做这个的,不就是正常的游戏客户端和服务器开发,软硬件联动,有啥恶心不恶心的,提前告诉你就是怕你接受不了,接受不了就没必要再往后走流程浪费时间,虽然这公司是一坨。
点赞 评论 收藏
分享
评论
39
收藏
分享

创作者周榜

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