JDK與設計模式:單例模式
阿新 • • 發佈:2019-02-06
單例模式用於建立那些在軟體系統中獨一無二的物件,例如資料庫管理物件,你希望在應用程式中共享該物件,完成對資料庫的統一管理以及某些軟體的引擎(如圖片渲染引擎),不同模組需要共享引擎提供的功能,而又不想建立多個引擎物件,因為引擎是一種耗資源的物件。
1、單例模式
單例模式定義:確保某一個類只有一個例項,而且自行例項化並向整個系統提供這個例項,這個類稱為單例類,他提供全域性訪問的方法。單例模式是一種建立型模式。
類圖:
實現注意事項:
(1)、建構函式設定為private私有,防止類外直接使用new關鍵字建立物件。
(2)、為了讓外界可以訪問這個唯一例項,需要為SingletonClass定義一個型別為SingletonClass的靜態私有成員變數instance。
(3)、instance類變數設定為私有,為了訪問、獲取該變數,需要增加一個公有的靜態方法SingletonClass getInstance()。
總結: 單例模式提供了對唯一例項的受控訪問,可以節約系統資源,對一些高資源消耗建立、銷燬的物件,可以提高效能。但是單例模式沒有抽象層,擴充套件較困難,而且職責過重,即提供了業務方法,又提供了建立物件的工廠,功能耦合。 2、JDK中單例模式應用 在JDK中java.lang.Runtime類,使用了餓漢式單例模式實現,保證了Runtime的唯一性。 原始碼如下:
- 餓漢式單例類
package com.xl.designPattern; public class EagerSingletonClass { private static EagerSingletonClass instance = new EagerSingletonClass(); private EagerSingletonClass(){ } public static EagerSingletonClass getInstance(){ return instance ; } }
- 懶漢式單例模式
package com.xl.designPattern; public class LazySingletonClass { private static LazySingletonClass instance = null; private LazySingletonClass(){ } synchronized public static LazySingletonClass getInstance(){ if(instance == null){ instance = new LazySingletonClass(); } return instance ; } }
- 靜態內部類式單例模式
package com.xl.designPattern; public class StaticHolderSingletonClass { private StaticHolderSingletonClass(){ } private static class HolderClass{ private static final StaticHolderSingletonClass instance = new StaticHolderSingletonClass(); } public static StaticHolderSingletonClass getInstance(){ return HolderClass.instance; } }
總結: 單例模式提供了對唯一例項的受控訪問,可以節約系統資源,對一些高資源消耗建立、銷燬的物件,可以提高效能。但是單例模式沒有抽象層,擴充套件較困難,而且職責過重,即提供了業務方法,又提供了建立物件的工廠,功能耦合。 2、JDK中單例模式應用 在JDK中java.lang.Runtime類,使用了餓漢式單例模式實現,保證了Runtime的唯一性。 原始碼如下:
public class Runtime {
private static Runtime currentRuntime = new Runtime(); //宣告私有的靜態類成員變數currentRuntime ,當類載入完成時,構造Runtime例項物件。
/**
* Returns the runtime object associated with the current Java application.
* Most of the methods of class <code>Runtime</code> are instance
* methods and must be invoked with respect to the current runtime object.
*
* @return the <code>Runtime</code> object associated with the current
* Java application.
*/
public static Runtime getRuntime() { //通過公有的靜態方法獲取唯一例項物件
return currentRuntime;
}
/** Don't let anyone else instantiate this class */
private Runtime() {} //建構函式私有化,保證類外不可建立該類物件
......
}