一、定義:確保一個類只有一個實例,并且自動實例化,并向整個系統提供這個實例。
二、使用場景:避免重復創建對象,過多消耗系統資源。
三、使用方式
????????3.1餓漢式:類加載時立即初始化,線程安全,可能會浪費資源。
public class Singleton {
? ? private static final Singleton INSTANCE = new Singleton();
? ? private Singleton() {} // 私有構造方法
? ? public static Singleton getInstance() {
? ? ? ? return INSTANCE;
? ? }
}
? ? ? ? 3.2懶漢式:需要使用實例時才進行初始化,多線程不安全。? ? ? ?
public class Singleton {
? ? private static Singleton instance;
? ? private Singleton() {}
? ? public static Singleton getInstance() {
? ? ? ? if (instance == null) {
? ? ? ? ? ? instance = new Singleton();
? ? ? ? }
? ? ? ? return instance;
? ? }
}
? ? ? ? 3.3雙重檢查鎖,DCL:使用時創建實例,使用雙重鎖校驗,線程安全。
public class Singleton {
? ? private static volatile Singleton instance;
? ? private Singleton() {}
? ? public static Singleton getInstance() {
? ? ? ? if (instance == null) {
? ? ? ? ? ? synchronized (Singleton.class) {
? ? ? ? ? ? ? ? if (instance == null) {
? ? ? ? ? ? ? ? ? ? instance = new Singleton();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return instance;
? ? }
}
? ? ? ? 3.4靜態內部類:使用類加載機制,延遲初始化,線程安全。
public class Singleton {
? ? private Singleton() {}
? ? private static class Holder {
? ? ? ? private static final Singleton INSTANCE = new Singleton();
? ? }
? ? public static Singleton getInstance() {
? ? ? ? return Holder.INSTANCE;
? ? }
}
? ? ? ? 3.5枚舉單例:簡潔、線程安全,且能防止反射和序列化破壞單例。
public enum Singleton {
? ? INSTANCE;
? ? public void doSomething() {
? ? ? ? // 功能代碼
? ? }
}