定義
??一個(gè)類至多有一個(gè)對(duì)象實(shí)例秒咐。這個(gè)實(shí)例被稱為單例漾抬。在使用時(shí)才初始化被稱為懶漢式單例,類一加載就初始化被叫做餓漢式單例碑诉。有8種常見實(shí)現(xiàn)方式玉凯。
實(shí)現(xiàn)
- 靜態(tài)常量法:可用
public class Singleton {
private final static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
- 靜態(tài)代碼塊:可用
public class Singleton {
private static Singleton instance;
static { instance = new Singleton(); }
private Singleton() {}
public Singleton getInstance() {
return instance;
}
}
- 靜態(tài)方法:不可用
public class Singleton {
private static Singleton singleton;
private Singleton() {}
public static Singleton getInstance() {
if (singleton == null)
singleton = new Singleton();
return singleton;
}
}
??線程A進(jìn)入第7句但還未來得及初始化時(shí),線程B在第5句判斷為null联贩,所以也可以進(jìn)入第6句漫仆,有并發(fā)問題。
- 同步方法:可用但不推薦
public class Singleton {
private static Singleton singleton;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (singleton == null)
singleton = new Singleton();
return singleton;
}
}
- 同步代碼塊:不可用
public class Singleton {
private static Singleton singleton;
private Singleton() {}
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
singleton = new Singleton();
}
}
return singleton;
}
}
??線程A進(jìn)入第7句但還未來得及初始化時(shí)泪幌,線程B在第5句判斷為null盲厌,雖然得等到A初始化完成,但也可以進(jìn)入第7句祸泪,有并發(fā)問題吗浩。
- 雙重檢查:可用且推薦用
public class Singleton {
private static volatile Singleton singleton;
private Singleton() {}
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
- 靜態(tài)內(nèi)部類:可用且推薦用
public class Singleton {
private Singleton() {}
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonInstance.INSTANCE;
}
}
- 枚舉:可用且推薦用
public enum Singleton {
INSTANCE;
public void whateverMethod() {
doSomethingHere...
}
}