题解 | #创建单例对象#

创建单例对象

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


}
全部评论

相关推荐

C9本港硕都给我挂了,好歹给个面试啊
丶西瓜:人太多,给他们惯的
投递海尔等公司9个岗位
点赞 评论 收藏
分享
落贝贝:同学,瞅瞅我司,医疗独角兽,校招刚开,名额有限,先到先得,我的主页最新动态,绿灯直达,免笔试~
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-17 14:06
点赞 评论 收藏
分享
评论
40
收藏
分享

创作者周榜

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