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方式来初始化达到优化的目的。

 

posted @ 2016-04-10 12:30  Jason Cai  阅读(6228)  评论(3编辑  收藏  举报