C# 单例模式Lazy<T>实现版本

ぐ巨炮叔叔 提交于 2019-11-26 20:28:05

非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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!