1. 程式人生 > >單例模式(Singleton Pattern)

單例模式(Singleton Pattern)

圖片 字段 == () 線程 配置 protected obj 類型

模式定義

單例模式(Singleton Pattern):單例模式確保某一個類只有一個實例,而且自行實例化並向整個系統提供這個實例,這個類稱為單例類,它提供全局訪問的方法。

  • 只能有一個實例
  • 必須自行創建
  • 自行向整個系統提供訪問

    UML類圖

    技術分享圖片

  • 私有靜態自身類型字段
  • 私有構造方法
  • 公有靜態函數返回自身對象

    代碼結構

    public static class SingletonApp
    {
        public static void Run()
        {
            Singleton s1 = Singleton.Instance();
            Singleton s2 = Singleton.Instance();
    
            if(s1 == s2)
            {
                Console.WriteLine("Objects are the same instance");
            }
        }
    }
    
    public class Singleton
    {
        private static Singleton _instance;
    
        protected Singleton()
        {}
        public static Singleton Instance()
        {
            if(_instance == null)
            {
                _instance = new Singleton();
            }
    
            return _instance;
        }
    }

    多線程代碼結構

    這裏介紹著名的雙鎖機制。

    public class Singleton
    {
        private static Singleton _instance;
        protected Singleton()
        { }
        public static Singleton Instance()
        {
            if (_instance == null)
            {
                lock (typeof(Singleton))
                {
                    if (_instance == null)
                    {
                        _instance = new Singleton();
                    }
                }
            }
            return _instance;
        }
    }

    C#語法優化

    我們用的C#語言,是高級、簡潔的語言。那麽更簡潔的寫法為:(註意關鍵詞readonly)

    public class Singleton
    {
        private static readonly Singleton _instance = new Singleton();
        protected Singleton()
        { }
        public static Singleton GetInstance()
        {
            return _instance;
        }
    }

    情景模式

    利用單例模式主要用來限制類只能實力化一個對象,所有訪問都訪問唯一一個對象。有時我們讀取配置文件時,創建單例模式。

單例模式(Singleton Pattern)