目录
七种写法的单列模式
版本1:饿汉式
public class SingletonObject1 {
private static final SingletonObject1 instance = new SingletonObject1();
private SingletonObject1() {
}
public static SingletonObject1 getInstance() {
return instance;
}
}
版本2:多线程可能导致多个实例
/**
多线程可能导致多个实例
*/
public class SingletonObject2 {
private static SingletonObject2 instance;
private SingletonObject2(){}
public static SingletonObject2 getInstance() {
if (null == instance){
instance = new SingletonObject2();
}
return instance;
}
}
版本3:效率有待优化
/**
将整个方法锁住,效率有待优化
*/
public class SingletonObject3 {
private static SingletonObject3 instance;
private SingletonObject3(){}
public synchronized static SingletonObject3 getInstance() {
if (null == instance){
instance = new SingletonObject3();
}
return instance;
}
}
版本4:Double Check可能出现空指针异常
/**
* Double Check
* 可能会导致空指针异常:
*/
public class SingletonObject4 {
private static SingletonObject4 instance;
private SingletonObject4(){}
public static SingletonObject4 getInstance() {
if (null == instance){
synchronized (SingletonObject4.class){
if (null == instance) {
instance = new SingletonObject4();
}
}
}
return instance;
}
}
版本5:Double Check
public class SingletonObject5 {
//volatile 保证读的过程,写必须完成,
// 也就new SingletonObject5的时候里面的内容全部构造完成
private volatile static SingletonObject5 instance;
private SingletonObject5(){}
public static SingletonObject5 getInstance() {
if (null == instance){
synchronized (SingletonObject5.class){
if (null == instance) { //这里一定需要再次判断
instance = new SingletonObject5();
}
}
}
return instance;
}
}
版本6:通过静态内部类构造
public class SingletonObject6 {
private SingletonObject6() {}
private static class InstanceHolder {
private final static SingletonObject6 instance = new SingletonObject6();
}
public static SingletonObject6 getInstance() {
return InstanceHolder.instance;
}
}
版本7:通过枚举构造
public class SingletonObject7 {
private SingletonObject7(){ }
private enum Singleton {
INSTANCE;
private final SingletonObject7 instance;
Singleton() {
instance = new SingletonObject7();
}
public SingletonObject7 getInstance() {
return instance;
}
}
public static SingletonObject7 getInstance() {
return Singleton.INSTANCE.getInstance();
}
}