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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值