题解 | #单例模式的关键点#

创建单例对象

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

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;
}

}

全部评论
好理解,通俗易懂
点赞 回复 分享
发布于 2023-09-04 14:44 山东

相关推荐

07-21 12:41
已编辑
门头沟学院 Java
steelhead:不是你的问题,这是社会的问题。
点赞 评论 收藏
分享
评论
18
2
分享

创作者周榜

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