标签:Lazy isDisposed C# ISingleton Dispose private 单例 public
原文链接:http://www.cnblogs.com/BrainDeveloper/p/5373808.html非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方式来初始化达到优化的目的。
转载于:https://www.cnblogs.com/BrainDeveloper/p/5373808.html
标签:Lazy,isDisposed,C#,ISingleton,Dispose,private,单例,public 来源: https://blog.csdn.net/weixin_30399871/article/details/99103199
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。