线程安全的单例模式 | DotNetExtensions知识点摘要(一)

    public class Singleton<T> : IDisposable where T : class
    {
        protected Singleton() { }

        protected static object[] mutex = new object[] { };
        protected static T _default;
        public static T Default
        {
            get
            {
                if (_default == null)
                {
                    lock (mutex)
                    {
                        if (_default == null)
                        {
                            Type type = typeof(T);
                            var ctor = type.GetConstructor(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, Type.DefaultBinder, Type.EmptyTypes, null);

                            if (ctor == null) throw new Exception($" type `{type.FullName}` miss a none paramters constructor .");

                            object instance = ctor.Invoke(null);

                            if (instance == null) throw new Exception($" type `{type.FullName}` miss a none paramters constructor .");

                            _default = (instance as T);
                        }
                    }
                }

                return _default;
            }
        }

        public void Dispose()
        {
            _default = null;
        }
    }

这是一种通过反射实例化单列对象,虽然反射会牺牲一些性能,但是单例至始至终也只会实例化一次,所以这点消耗是可以接受的。

    // 使用继承方式,实现单例
    public class HttpClientFactory : Singleton<HttpClientFactory>
    {
        public enum HttpClientKind
        {
            Restful = 0,
            File = 1
        }
        private readonly ConcurrentBag<IHttpClient> httpClents;

        // 可以私有化构造函数,外部无法构造此对象,实现真正意义的单例。
        private HttpClientFactory()
        {
            httpClents = new ConcurrentBag<IHttpClient>();
        }

        ...
    }

优点:复用性好,可以私有化构造函数

缺点:反射消耗性能(可以忽略不计)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值