星空网 > 软件开发 > ASP.net

C# 单例模式LazyT实现版本

非Lazy版本的普通单例实现:

  public sealed class SingletonClass : ISingleton  {    private SingletonClass ()    {      // the private contructors    }    public static ISingleton Instance    {      get      {        if (instance == null)        {          lock (InstanceLock)          {            if (instance != null)            {              return instance;            }            instance = new SingletonClass();          }        }        return instance;      }    }    private static ISingleton instance;    private static readonly object InstanceLock = new object();           private bool isDisposed;    // other properties        public void Dispose()    {      this.Dispose(true);      GC.SuppressFinalize(this);     }    private void Dispose(bool disposing)    {      if (!this.isDisposed)      {        if (disposing)        {          // dispose the objects you declared        }        this.isDisposed = true;      }    }  }  public interface ISingleton : IDisposable  {    // your interface methods  }

 

Lazy版本的单例实现:

  public sealed class SingletonClass : ISingleton  {    private SingletonClass ()    {      // the private contructors    }    public static ISingleton Instance = new Lazy<ISingleton>(()=> new new SingletonClass()).Value;

private static readonly object InstanceLock = new object(); private bool isDisposed; // other properties public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (!this.isDisposed) { if (disposing) { // dispose the objects you declared } this.isDisposed = true; } } } public interface ISingleton : IDisposable { // your interface methods }

 

对比分析:

使用Lazy<T>来初始化,使得代码看起来更为简洁易懂。其实非Lazy<T>版本的单例实现从本质上说就是一个简单的对象Lazy的实现。

一般对于一些占用大的内存的对象,常常使用Lazy方式来初始化达到优化的目的。

 




原标题:C# 单例模式LazyT实现版本

关键词:C#

C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

国外名牌男鞋:https://www.goluckyvip.com/tag/80455.html
光伏产业市场:https://www.goluckyvip.com/tag/8046.html
东盟高校:https://www.goluckyvip.com/tag/8047.html
阿里1688:https://www.goluckyvip.com/tag/8048.html
阿里商业:https://www.goluckyvip.com/tag/8049.html
增长速度飞快:https://www.goluckyvip.com/tag/805.html
千岛湖绿城度假酒店的简介:https://www.vstour.cn/a/363185.html
深圳大湾区游轮夜景 深圳大湾区游轮夜景图:https://www.vstour.cn/a/363186.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流