我是獨(dú)一無二的『單例模式』

目錄:設(shè)計模式之小試牛刀
源碼路徑:Github-Design Pattern


定義:(Singleton Pattern)

確保某一個類只有一個實(shí)例,而且自行實(shí)例化并向整個系統(tǒng)提供這個實(shí)例。

類圖:

應(yīng)用場景:

避免產(chǎn)生多個對象消耗過多的資源(特別是一個對象需要頻繁的創(chuàng)建和銷毀時);
提供一個全局訪問點(diǎn),常常被用來管理系統(tǒng)中共享的資源(作為一個Manager)。

實(shí)現(xiàn)方式:

一、靜態(tài)變量初始化(餓漢模式)

代碼:

    /// <summary>
    /// 單例模式實(shí)現(xiàn)方式一:
    /// 靜態(tài)變量初始化
    /// </summary>
    public class Singleton1
    {
        /// <summary>
        /// 定義為靜態(tài)變量,由所有對象共享
        /// </summary>
        private static Singleton1 instance = new Singleton1();
        
        /// <summary>
        /// 構(gòu)造函數(shù)私有化,禁止外部類實(shí)例化該類對象
        /// </summary>
        private Singleton1()
        {
            
        }

        public static Singleton1 Instance()
        {
            return instance;
        }
}

應(yīng)用場景:

適用于單線程應(yīng)用程序


二、延遲初始化(懶漢模式)

代碼:

    /// <summary>
    /// 單例模式實(shí)現(xiàn)方式二:
    /// 延遲初始化
    /// </summary>
    public class Singleton2
    {
        /// <summary>
        /// 定義為靜態(tài)變量,由所有對象共享
        /// </summary>
        private static Singleton2 _instance;

        /// <summary>
        /// 構(gòu)造函數(shù)私有化,禁止外部類實(shí)例化該類對象
        /// </summary>
        private Singleton2()
        {
            
        }

        public static Singleton2 Instance()
        {
            return _instance ?? (_instance = new Singleton2());
        }
}

三、鎖機(jī)制(推薦)

代碼:

    /// <summary>
    /// 單例模式實(shí)現(xiàn)方式三:
    /// 鎖機(jī)制,確保多線程只產(chǎn)生一個實(shí)例
    /// </summary>
    public class Singleton3
    {
        private static Singleton3 _instance;

        private static readonly object Locker =new object();

        private Singleton3() { }

        public static Singleton3 Instance()
        {
            //沒有第一重 instance == null 的話,每一次有線程進(jìn)入 GetInstance()時,均會執(zhí)行鎖定操作來實(shí)現(xiàn)線程同步,
            //非常耗費(fèi)性能 增加第一重instance ==null 成立時的情況下執(zhí)行一次鎖定以實(shí)現(xiàn)線程同步
            if (_instance==null)
            {
                lock (Locker)
                {
                    //Double-Check Locking 雙重檢查鎖定
                    if (_instance==null)
                    {
                        _instance = new Singleton3();
                    }
                }
            }

            return _instance;
        }
}

四、泛型單例模式

代碼:

/// <summary>
    /// 泛型單例模式的實(shí)現(xiàn)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class GenericSingleton<T> where T : class//,new ()
    {
        private static T instance;

        private static readonly object Locker = new object();

        public static T GetInstance()
        {
            //沒有第一重 instance == null 的話,每一次有線程進(jìn)入 GetInstance()時,均會執(zhí)行鎖定操作來實(shí)現(xiàn)線程同步,
            //非常耗費(fèi)性能 增加第一重instance ==null 成立時的情況下執(zhí)行一次鎖定以實(shí)現(xiàn)線程同步
            if (instance == null)
            {
                //Double-Check Locking 雙重檢查鎖定
                lock (Locker)
                {
                    if (instance == null)
                    {
                        //instance = new T();
                        //需要非公共的無參構(gòu)造函數(shù),不能使用new T() ,new不支持非公共的無參構(gòu)造函數(shù) 
                        instance = Activator.CreateInstance(typeof(T), true) as T;//第二個參數(shù)防止異常:“沒有為該對象定義無參數(shù)的構(gòu)造函數(shù)?!?                    }
                }
            }
            return instance;
        }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容