单例模式
饿汉式(急切实例化)
public class EagerSingleton {
/** 1.私有化构造方法 */
private EagerSingleton() {
}
/** 2.声明静态成员变量并赋初始值-类初始化的时候静态变量就被加载,因此叫做饿汉式 */
public static EagerSingleton eagerSingleton=new EagerSingleton();
/** 3.对外暴露公共的实例化方法 */
public static EagerSingleton getInstance(){
return eagerSingleton;
}
}
懒汉式(延迟实例化)(DCL双重检测)
-为什么要判断两次?
避免由于并发导致的线程安全问题
-为什么要使用 volatile关键字修饰 ourInstance?
避免指令重排序,同时保证变量ourInstance在线程之间是可见的
public class LazySingleton {
/** 1.私有化构造方法 */
private LazySingleton() {
}
/** 2.声明静态变量 -这里声明为volatile,是禁止指令重排序 */
private volatile static LazySingleton ourInstance;
/** 3.对外暴露公共的实例化方法 */
public static LazySingleton getInstance() {
if (ourInstance == null) {
synchronized (LazySingleton.class) {
if (ourInstance == null) {
ourInstance = new LazySingleton();
}
}
}
return ourInstance;
}
}