c#設計模式----單例模式

設計模式中有許多設計模式,今天學了單例模式來鞏固一下。爲什麼要用單例模式,優缺點是什麼,什麼是單例模式。

爲什麼要用單例模式:在編寫程序中,多次初始化同一個類耗費時間,內存等,單例模式表示只new一個對象,在單線程,多線程中也一樣,只new一個對象。

優缺點是什麼:單例模式中,一直佔用內存,不GC。普通模式new出來以後,用完GC,不佔用內存,資源。

單例模式有三種形態,最常用的是雙if加lock。

        private SmoothType()//私有構造函數
        {
            this.InitializeComponent();
        }

        private static SmoothType smoothType = null;
        private static readonly object smoothType_lock = new object();
        public static SmoothType GetInstance()
        {
            if (smoothType == null)//減少因lock產生的時間,資源損耗
            {
                lock (smoothType_lock)//防止多線程,調用多次初始化
                {
                    if (smoothType == null) // 當未初始化時,初始化
                    {
                        smoothType = new SmoothType();
                    }
                }
            }
            return smoothType;
        }

上面就是最常用的雙if加lock形態。

        private SmoothType()
        {
            this.InitializeComponent();
        }

        private static SmoothType smoothType = new SmoothType();//簡化型單例,由clr保證只實例化一次
        public static SmoothType GetInstance()
        {
            return smoothType;
        }

上面是簡略型單例模式

        private SmoothType()//私有構造函數
        {
            this.InitializeComponent();
        }

        private static SmoothType smoothType = null;
        private static readonly object smoothType_lock = new object();
        public static SmoothType GetInstance()
        {
                    if (smoothType == null) // 當未初始化時,初始化
                    {
                        smoothType = new SmoothType();
                    }
            return smoothType;
        }

單例模式第三種形態

一般都用第一種,雙if加lock形態

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章