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

34次阅读

共计 730 个字符,预计需要花费 2 分钟才能阅读完成。

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

正文完
 0