C# 单例模式Lazy<T>实现版本
非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方式来初始化达到优化的目的。
作者:Jason Cai
出处:http://www.cnblogs.com/BrainDeveloper/
本文版权归作者(Jason Cai)所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/BrainDeveloper/
本文版权归作者(Jason Cai)所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。