1 概述
本章主要與大家分享【設計模式系列】之單利模式內容,結合具體代碼與大家一起分享。
2 具體講解
2.1 結合代碼分析
第一種(懶漢,線程不安全):
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; } }
第三種(餓漢):
1 public class Singleton { 2 private static Singleton instance = new Singleton(); 3 private Singleton (){} 4 public static Singleton getInstance() { 5 return instance; 6 } 7 }
第四種(餓漢,變種):
public class Singleton { private Singleton instance = null; static { instance = new Singleton(); } private Singleton (){} public static Singleton getInstance() { return this.instance; } }
第五種(靜態內部類):
1 public class Singleton { 2 private static class SingletonHolder { 3 private static final Singleton INSTANCE = new Singleton(); 4 } 5 private Singleton (){} 6 public static final Singleton getInstance() { 7 return SingletonHolder.INSTANCE; 8 } 9 }
第六種(枚舉):
1 public enum Singleton { 2 INSTANCE; 3 public void whateverMethod() { 4 } 5 }
第七種(雙重校驗鎖):
1 public class Singleton { 2 private volatile static Singleton singleton; 3 private Singleton (){} 4 public static Singleton getSingleton() { 5 if (singleton == null) { 6 synchronized (Singleton.class) { 7 if (singleton == null) { 8 singleton = new Singleton(); 9 } 10 } 11 } 12 return singleton; 13 } 14 }
2.2 總結
(1)單例模式,從字面意思上理解,“單例”,即只有唯一一個實例,通常情況下,定義一個類,然后通過new ClassName()方式來產生具體對象,然而這樣,破壞了一個類只有一個實例,怎么處理該問題呢?將類的具體化放在類的構造函數來完成;
(2)如上方式解決了單例問題,然而,外界如何才能訪問該類?很簡單,該類提供一個全局的訪問點即可;
(3)根據以上(1),(2)步驟的划分,單例模式有2個很明顯特點:a.類只有一個實例 b.類必須提供全局唯一的可被訪問點;
4 參考文獻
【01】《大話設計模式》(中文版),《design patterns:elements of reusable object-oriented software》(英文版)
【02】《設計模式》(可復用面向對象軟件的基礎)(中文版),《Design Patterns Elements of Reusable Object-Oriented Software》(英文版)
【03】《Head First設計模式》(中文版), 《Head First Design Patterns》(英文版)
【04】《C#設計模式》(中文版),《C# Design Patterns:A Tutorial》(英文版)
【05】《Java企業設計模式》(中文版),《Java Enterprise Design Patterns》(英文版)
【06】 《UML和模式應用》(面向對象分析與設計導論)(中文版), 《Applying UML and Patterns:An Introduction to Object-Oriented Analysis and Design》(英文版)
【07】 《設計模式解析》(中文版),《Design Patterns Explained:A New Perspective on Object-Oriented Design》
【08】 《.NET 設計規范--.NET約定、慣用法與模式》(中文版),《Framework Design Guidelines : Conventions, Idioms, and Patterns for Reusable .NET Libraries》(英文版)
【09】 《重構與模式》(中文版),《Refactoring to Patterns》(英文版)
【10】 《設計模式解析》(中文版),《Design Patterns Explained:A New Perspective on Object-Oriented Design ,Second Edition》(英文版)
【11】 《深入淺出設計模式》(中文版),(C#/Java版)
【12】 《多線程與並發處理》
【13】 《企業應用架構模式》 (中文版),《Patterns of Enterprise Application Architecture》(英文版)
6 版權
- 感謝您的閱讀,若有不足之處,歡迎指教,共同學習、共同進步。
- 博主網址:http://www.cnblogs.com/wangjiming/。
- 極少部分文章利用讀書、參考、引用、抄襲、復制和粘貼等多種方式整合而成的,大部分為原創。
- 如您喜歡,麻煩推薦一下;如您有新想法,歡迎提出,郵箱:2016177728@qq.com。
- 可以轉載該博客,但必須著名博客來源。