[設計模式練習]獨體模式

[設計模式練習]獨體模式

只能建立物體一次

以後每次調用相同的物件

類別圖

Singleton

物件檔定義


using System.Collections.Generic;
using System.Text;

namespace DesignModelTest.獨體
{
    /// <summary>
    /// 獨體模式
    /// </summary>
    class Singleton
    {
        private static Singleton instance;
        private Singleton()//私有化建構式
        {
        }
        public static Singleton GetInstance()//全域存取函式來控制物件建立
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
    /// <summary>
    /// 使用DoubleCheck(多執行緒)
    /// </summary>
    class SingletonDoubleCheck
    {
        private static SingletonDoubleCheck instance;
        private static readonly object syncRoot = new object();
        private SingletonDoubleCheck()
        {
        }        
        public static SingletonDoubleCheck GetInstance()
        {

            if (instance == null)// 1st check
            {
                lock (syncRoot)//lock the status
                {
                    if (instance == null)//2nd check
                    {
                        instance = new SingletonDoubleCheck();
                    }
                }
            }
            return instance;
        }
    }
    /// <summary>
    /// 使用sealed:不能被繼承
    /// </summary>
    public sealed class SealedSingleton
    {
        private static readonly SealedSingleton instance = new SealedSingleton();
        private SealedSingleton() { }
        public static SealedSingleton GetInstance()
        {
            return instance;
        }
    }

}

用戶端程式碼


            //獨體模式
            DesignModelTest.獨體.Singleton s1 = DesignModelTest.獨體.Singleton.GetInstance();
            DesignModelTest.獨體.Singleton s2 = DesignModelTest.獨體.Singleton.GetInstance();
            Console.WriteLine((s1 == s2) ? "相等" : "不相等");
            //使用DoubleCheck
            DesignModelTest.獨體.SingletonDoubleCheck s3 = DesignModelTest.獨體.SingletonDoubleCheck.GetInstance();
            DesignModelTest.獨體.SingletonDoubleCheck s4 = DesignModelTest.獨體.SingletonDoubleCheck.GetInstance();
            Console.WriteLine((s3 == s4) ? "相等" : "不相等");
            //使用sealed
            DesignModelTest.獨體.SealedSingleton s5 = DesignModelTest.獨體.SealedSingleton.GetInstance();
            DesignModelTest.獨體.SealedSingleton s6 = DesignModelTest.獨體.SealedSingleton.GetInstance();
            Console.WriteLine((s5 == s6) ? "相等" : "不相等");
            Console.Read();
            #endregion

輸出結果

pic1