1. 單例模式:飽漢、餓漢。以及餓漢中的延遲加載,雙重檢查
1)餓漢模式:
//餓漢模式,很餓很着急,所以類加載時即創建實例對象
public class Singleton1 {
private static Singleton1 singleton = new Singleton1();
private Singleton1(){
}
public static Singleton1 getInstance(){
return singleton;
}
}
2)飽漢模式:
//飽漢模式,很飽不着急,延遲加載,啥時候用啥時候創建實例,存在線程安全問題
public class Singleton2 {
private static Singleton2 singleton;
private Singleton2(){
}
public static synchronized Singleton2 getInstance(){
if(singleton == null)
singleton = new Singleton2();
return singleton;
}
}
3)雙重鎖模式:
//飽漢模式的雙重鎖模式,提高效率
public class Singleton3 {
private static Singleton3 singleton;
private Singleton3(){
}
public static Singleton3 getInstance(){
if(singleton == null){
synchronized(Singleton3.class){
if(singleton == null){
singleton = new Singleton3();
}
}
}
return singleton;
}
}
幾種模式的比較:
1、餓漢模式是線程安全的,因爲實例對象在類加載過程中就會被創建,在getInstance()方法中只是直接返回對象引用。之所以被稱爲“餓漢”,是因爲這種模式創建實例對象比較“急”,真的是餓壞了.
好處:簡單明瞭,無需關注線程安全問題。
缺點:如果在一個大環境下使用了過多的餓漢單例,則會生產出過多的實例對象,無論你是否要使用他們。
2、飽漢模式不是線程安全的,因爲是在需要的時候纔會產生實例對象,生產之前會判斷對象引用是否爲空,這裏,如果多個線程同時進入判斷,就會生成多個實例對象,這是不符合單例的思想的。所以飽漢模式爲了保證線程安全,就用synchronized關鍵字標識了方法。之所以被稱爲“飽漢”,因爲它很飽,不急着生產實例,在需要的時候纔會生產。
好處:延時加載,用的時候纔會生產對象。
缺點:需要保證同步,付出效率的代價。
3、雙重鎖模式,是飽漢模式的優化,進行雙重判斷,當已經創建過實例對象後就無需加鎖,提高效率。也是一種推薦使用的方式。
2. 工廠模式、裝飾者模式、觀察者模式。
參考:
《設計模式(四)-工廠模式(Factory Method Pattern/Factory Pattern)——將實例的生成交給子類》
《設計模式(十二)-裝飾器模式(Decorator Pattern)——裝飾邊框與被飾物的一致性》
《設計模式(十七)-觀察者模式(Observer Pattern)——發送狀態變化通知》
3. 工廠方法模式的優點(低耦合、高內聚,開放封閉原則)
參考:
《 設計模式(四)-工廠模式(Factory Method Pattern/Factory Pattern)——將實例的生成交給子類》