基于C#的设计模式学习之单例模式

单例模式,一个类只构建唯一的对象。分为饿汉式和懒汉式。

饿汉式是类加载到内存就实例类的的唯一实例。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Designmode.Singleton
{
    /// <summary>
    /// 饿汉模式,类加载到内存后只实例化一个单例
    /// 优点:简单使用
    /// 缺点:开始的时候就完成实例构造
    /// </summary>
    public class ManagerA
    {
        /// <summary>
        /// 私有实例
        /// </summary>
        private static ManagerA _instance = new ManagerA();
        /// <summary>
        /// 构造一个Manager实例,私有属性,外部无法构造
        /// </summary>
        private ManagerA()
        {

        }
        /// <summary>
        /// 获取私有实例
        /// </summary>
        /// <returns>返回开始构造私有实例</returns>
        public static ManagerA GetInstance()
        {
            return _instance;
        }
    }
}

懒汉式,类加载到内存时并不构造唯一实例,需要在使用时候才构造。代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Designmode.Singleton
{
    /// <summary>
    /// lazy loading 懒汉式
    /// </summary>
    public class ManagerB
    {
        /// <summary>
        /// 私有实例
        /// </summary>
        private static ManagerB _instance = null;
        /// <summary>
        /// 安全锁
        /// </summary>
        private static object _lockObj = new object();
        /// <summary>
        /// 获取私有实例,开始时实例为null,需要创建,后续不需创建
        /// </summary>
        /// <returns></returns>
        public static ManagerB GetInstance()
        {
            lock (_lockObj)/// 存在线程不安全的问题,可以通过加锁实现线程安全,但是增加开销
            {
                if (_instance is null)
                {
                    
                    _instance = new ManagerB();
                }
            }
            return _instance;
        }
    }
}

推荐通过Lazy关键字实现单例模式Lazy提供延迟初始化功能,可以先声明某个对象,当第一次使用的时候才被初始化,如果一直未被调用,将会一直不被初始化,省去了一部分不必要的开销,提升了效率,同时Lazy是天生线程安全的,实现懒汉式的单例,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Designmode.Singleton
{
    /// <summary>
    /// 通过Lazy关键字,实现单例模式
    /// </summary>
    public class ManagerC
    {
        /// <summary>
        /// 延迟初始化私有实例,具备线程安全
        /// </summary>
        private static readonly Lazy<ManagerC> Lazy = new Lazy<ManagerC>(() => new ManagerC(), true);

        /// <summary>
        /// 构造一个Manager实例,私有属性,外部无法构造
        /// </summary>
        private ManagerC()
        {

        }
        /// <summary>
        /// 获取私有实例
        /// </summary>
        /// <returns>返回开始构造私有实例</returns>
        public static ManagerC GetInstance()
        {
            return Lazy.Value;
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值