设计模式-单例模式

//单例饿汉
public class Singleton01 {
    private static final Singleton01 INSTANCE = new Singleton01();

    private Singleton01() {
    }

    public static Singleton01 getInstance() {
        return INSTANCE;
    }
}
public class Singleton02 {
    private volatile static Singleton02 INSTANCE;
    //为何要使用volatile
    //执行构造方法和赋值的操做可能会指令重排序,并发状况下可能有两个对象被初始化
    //故使用volatile,禁止指令重排序,保证线程安全
    private Singleton02() {}

    public static Singleton02 getInstance() {
        if (INSTANCE == null) {
            synchronized (Singleton02.class) {
                if (INSTANCE == null) {
                    INSTANCE = new Singleton02();
                }
            }
        }
        return INSTANCE;
    }
}
public class Singleton03 {
    private Singleton03() {
    }
    //静态内部类自带懒加载
    private static class SingletonHolder {
        private static Singleton03 INSTANCE = new Singleton03();
    }

    public static Singleton03 getInstance() {
        return SingletonHolder.INSTANCE;
    }

}
public enum Singleton04 {
    //枚举
    INSTANCE;
}
相关文章
相关标签/搜索