一、懶漢式
1.1 雙重檢查機制
package com.study.single_instance.java.lazy;
public class DoubleCheckSingleInstance {
private volatile static DoubleCheckSingleInstance doubleCheckSingleInstance=null;
private DoubleCheckSingleInstance(){}
public static DoubleCheckSingleInstance getInstance(){
if(doubleCheckSingleInstance==null){
synchronized (DoubleCheckSingleInstance.class) {
if(doubleCheckSingleInstance==null) {
doubleCheckSingleInstance = new DoubleCheckSingleInstance();
}
}
}
return doubleCheckSingleInstance;
}
}
1.2 靜態內部類的方式
package com.study.single_instance.java.lazy;
public class StaticClassSingleInstance {
private static StaticClassSingleInstance staticClassSingleInstance=null;
private StaticClassSingleInstance(){ }
private static class InnerInstanceHolder{
private static StaticClassSingleInstance staticClassSingleInstance=new StaticClassSingleInstance();
}
public static StaticClassSingleInstance getInstance(){
return InnerInstanceHolder.staticClassSingleInstance;
}
}
二、餓漢式
2.1 成員變數初始化
package com.study.single_instance.java.hungry;
import java.io.Serializable;
public class LazySingleInstance implements Serializable,Cloneable {
private final static LazySingleInstance lazySingleInstance=new LazySingleInstance();
private LazySingleInstance(){}
public static LazySingleInstance getInstance(){
return lazySingleInstance;
}
public Object readResolve(){
return lazySingleInstance;
}
}
2.2 成員變數靜態程式碼塊初始化
package com.study.single_instance.java.hungry;
public class LazyStaticInitSingleInstance {
private final static LazyStaticInitSingleInstance lazyStaticSingleInstance;
static {
lazyStaticSingleInstance = new LazyStaticInitSingleInstance();
}
private LazyStaticInitSingleInstance(){}
public static LazyStaticInitSingleInstance getInstance(){
return lazyStaticSingleInstance;
}
}
三、多執行緒除錯方法