关于设计模式:设计模式单例模式

//单例饿汉
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;
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理