1呕缭、餓漢恢总。線程安全睬愤,類裝載時(shí)就實(shí)例化。
public class SingleInstance {
private SingleInstance(){}
private static SingleInstance mSingleInstance = new SingleInstance();
public static SingleInstance getInstance(){
return mSingleInstance;
}
}
2砂豌、懶漢。懶加載阳距,效率較低结借。
public class SingleInstance {
private SingleInstance(){}
private static SingleInstance mSingleInstance;
public static synchronized SingleInstance getInstance(){
if (mSingleInstance == null) {
mSingleInstance = new SingleInstance();
}
return mSingleInstance;
}
}
3、雙重校驗(yàn)鎖蓄拣。使用volatile變量,輕量級的同步機(jī)制球恤。
public class SingleInstance {
private SingleInstance(){}
private volatile static SingleInstance mSingleInstance;
public static SingleInstance getInstance(){
if (mSingleInstance == null) {
synchronized (SingleInstance.class) {
if (mSingleInstance == null) {
mSingleInstance = new SingleInstance();
}
}
}
return mSingleInstance;
}
}
4荸镊、靜態(tài)內(nèi)部類
public class SingleInstance {
private SingleInstance(){}
public static SingleInstance getInstance(){
return SingleHolder.instance;
}
private static class SingleHolder {
private static SingleInstance instance = new SingleInstance();
}
}
5堪置、枚舉
public enum SingleInstance {
INSTANCE;
}