早上隨便翻到單例的寫法错览,那我也隨手寫幾個吧
public class SingleClassTest {
//定義一個private的構(gòu)造方法纫雁,就是防止外部通過new SingleClassTest去實例化
private SingleClassTest(){}
//普通餓漢寫法
private static final SingleClassTest INSTANCE = new SingleClassTest();
private static SingleClassTest getInstance(){
return INSTANCE;
}
//普通懶漢寫法
private static SingleClassTest INSTANCE = null;
private static SingleClassTest getInstance(){
if (INSTANCE == null){
INSTANCE = new SingleClassTest();
}
return INSTANCE;
}
//禁止重排序,double-check寫法
private static volatile SingleClassTest INSTANCE = null;
private static SingleClassTest getInstance(){
if (INSTANCE == null){
synchronized (SingleClassTest.class){
if (INSTANCE == null){
INSTANCE = new SingleClassTest();
}
}
}
return INSTANCE;
}
//靜態(tài)內(nèi)部類寫法
private static SingleClassTest getInstance(){
return InnerSingleClass.INSTANCE;
}
private static class InnerSingleClass{
private static final SingleClassTest INSTANCE = new SingleClassTest();
}
}
除了以下幾種倾哺,需要知道枚舉也是屬于一種實現(xiàn)方式轧邪,并且它可以防止序列化/反序列化刽脖、反射
public enum SingleClassTest {
INSTANCE;
public static SingleClassTest getInstance(){
return INSTANCE;
}
}