单例模式

What

保证一个类只有一个实例,并提供它的全局唯一访问点。

保证一个Class只有一个实体对象存在。
具体可以有很多种,只有保证全局唯一就可以

初始化就创建

public class Singleton {
    private Singleton() {
    }

    private static Singleton instance = new Singleton();

    public static Singleton getInstance()
    {
        return instance;
    }

}

lazy load

当用的时候再创建。

public class SingletionLazy {
    private SingletionLazy() {}
    private static SingletionLazy instance = null;
    public static synchronized SingletionLazy getInstance()
    {
        if(instance == null)
            instance = new SingletionLazy();
        return instance;
    }
}

double check
两次检查null

public class Singleton{
    private static Singleton singleton;
    private Singleton (){}
    public static Singleton getSingleton() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容