// 饿汉单例模式 类加载时即创建实例对象。获取对象的速度快
public class EagerSingleton {
private EagerSingleton() {}
private static EagerSingleton instance = new EagerSingleton(); // 静态私有变量,已初始化
public static EagerSingleton getInstance() { // 静态公共方法,不用同步(类加载时已初始化,不会有多线程的问题),也不需要判断 null
return instance;
}
}
// 双重锁单例模式 进行双重判断,当已经创建过实例对象后就无需加锁
public class SingletonDCL {
private SingletonDCL() {}
private static volatile SingletonDCL obj;
public static SingletonDCL getInstance() {
if ( obj == null ) {
synchronized ( SingletonDCL.class ) {
if ( obj == null ) {
obj = new SingletonDCL();
}
}
}
return obj;
}
}