單例模式----設計模式之禪讀書筆記

單例模式 確保一個類只有一個實例,而且自行實例化並向系統提供這個實例。

Singleton Pattern  Ensure a class has only one instance,and provide a global point of access to it.

Singleton類稱爲單例類,通常使用private的構造函數確保樂在一個應用中只產生一個實例,並且是自行實例化的(在Singleton中自己使用new Singleton())。

單例模式通用代碼:

private class Singleton {

private static final Singleton singleton =new Singleton();

//限制產生多個對象

private Singleton (){

}

public static Singleton getSingleton(){

return singleton;

}

//orhers method

}

單例模式的優點

a)由於單例模式在內存中只有一個實例,減少了內存開支,特別是一個對象需要頻繁的創建銷燬時,而創建銷燬時的性能又無法優化單例模式的性能非常明顯。

單例模式的缺點

單例模式沒有接口,擴展困難

單例模式是自行實例化的接口對單例模式沒有任何意義接口或抽象是不可能被實例化的

單例模式與單一職則原則有衝突,一個類應該只能實現一個邏輯。

單例模式應用場景

要求生成唯一序列號的環境;

在整個項目中需要共享訪問點或者共享數據。使用單例模式保持計數器的值,並確保線程是安全的;

創建一個對象需要消耗的資源過多 Eg訪問IO 數據庫

需要定義大量的靜態常量和靜態方法(工具類的環境)

單例模式注意事項

懶漢模式

public class Singleton {

private static Singleton singleton =null;

private Singleton(){

if(singleton==null){

singleton = new Singleton();

}

return singleton;

}

}

餓漢模式

在函數前加synchronized關鍵字

 單例模式擴展

class Singleton{

private static int maxNumOfSingleton=2;//定義最多能產生的實例數

private  static ArrayList <String> nameList =  new ArrayList<String>();

private static ArrayList<Singleton> singleList = new ArralyList<Singleton>();

private static int countNumOfSingleton=0;static{

for(int i=0;i<maxNumOfSingleton;i++){

 singleList.add(new Singleton());

}

}

private Singleton(){

}

private Singleton(String name){

namelist.add(name);

}

public static Singleton getInstance(){

Random random = new Random();

countNUmOfSingleton =random.nextInt(maxNumOfSingle);

return singletonList.get(countNumOfSingleton);

}

//orther method

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章