其他分享
首页 > 其他分享> > 单例模式 懒汉式

单例模式 懒汉式

作者:互联网

线程不安全

class Singleton {
    private Singleton() {
    }

    private static Singleton instance;

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

线程安全

class Singleton {
    private static Singleton instance;

    private Singleton(){}

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

 

标签:Singleton,return,getInstance,模式,instance,static,private,单例,懒汉
来源: https://www.cnblogs.com/tsai-87/p/16143903.html