天天看點

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方式來初始化達到優化的目的。