參考鏈接: 單例模式
一、實現對比
| 推薦指數 | 實現方式 | 多線程安全 | Lazy初始化 | 實現難度 | 內存消耗 | 執(zhí)行效率 | JDK版本 |
|---|---|---|---|---|---|---|---|
| **** | 枚舉 | 是 | 否 |
易 | 良 |
高 | 1.5+ |
| **** | 餓漢式 | 是 | 否 |
易 | 良 |
高 | - |
| *** | 靜態(tài)內部類 | 是 | 是 | 一般 |
優(yōu) | 高 | - |
| ** | 雙檢鎖/雙重校驗鎖(DCL) | 是 | 是 | 復雜 |
優(yōu) | 高 | 1.5+ |
| * | 懶漢式(非線程安全) | 否 |
是 | 易 | 優(yōu) | 高 | - |
| * | 懶漢式(線程安全) | 是 | 是 | 易 | 優(yōu) | 極低 |
- |
二、實現方式
懶漢式(非線程安全)
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
懶漢式(線程安全)
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
[推薦] 餓漢式
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}
Classloder機制避免了多線程的同步問題
雙檢鎖/雙重校驗鎖(DCL)
public class Singleton {
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
[推薦] 靜態(tài)內部類
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
Classloder機制避免了多線程的同步問題
[推薦] 枚舉
public enum Singleton {
INSTANCE;
public static Singleton getInstance() {
return INSTANCE;
}
public void method() {
}
}