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形态

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