單例模式

```
單例模式 >>> 對象建立模式 >>> 確保一個類只有一個實例
```
```
只有一個實例、類內部建立惟一實例、對外提供該惟一實例
```
```
// ①懶漢式,線程不安全
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;
    }
}
// 線程安全、但並不高效、同一時刻只能有一個線程訪問該方法、同步操做只須要在第一次調用建立對象時才被須要、獲取對象時並不須要同步

```
```
// ③雙重檢驗鎖
// 雙重檢驗鎖模式(double checked locking pattern),是一種使用同步塊加鎖的方法
public class Singleton {
    private static Singleton instance;
    private Singleton (){}

    public static Singleton getInstance() {
    if (instance == null) {                         //Single Checked
        synchronized (Singleton.class) {
            if (instance == null) {                 //Double Checked
                instance = new Singleton();      // 並不是是一個原子操、jvm存在指令重排序的優化做、分配內存、初始化、指向內存空間、
            }
        }
    }
    return instance ;
  }
}
```
```
// ③雙重檢驗鎖 優化 volatile 
public class Singleton {
    private volatile static Singleton instance; //聲明成 volatile
    private Singleton (){}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
    
}
```
```
// ④餓漢式 static final field
public class Singleton {
    // 在裝載類的時候就建立對象實例
    private  static final Singleton instance=new Singleton();
    private Singleton (){}

    public static Singleton getInstance() {
        return instance;
    }
}
// 非惰性加載模式、沒法在實例的建立依賴參數或者配置文件的時候使用、在 getInstance() 以前必須調用某個方法設置參數給它,那樣這種單例寫法就沒法使用了
```
```
// ⑤靜態內部類 static nested class
// 這種方法也是《Effective Java》上所推薦的
public class Singleton {  
    private static class SingletonHolder {  
        private static final Singleton INSTANCE = new Singleton();  
    }  
    private Singleton (){}  
    public static final Singleton getInstance() {  
        return SingletonHolder.INSTANCE; 
    }  
}
```
```
// ⑥枚舉 Enum
public enum Singleton{
    INSTANCE;
}
```
相關文章
相關標籤/搜索