zoukankan      html  css  js  c++  java
  • 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方式来初始化达到优化的目的。

  • 相关阅读:
    Serveral effective linux commands
    Amber learning note A8: Loop Dynamics of the HIV-1 Integrase Core Domain
    amber初学……
    anaconda使用
    python中的一些语法
    python中的OOP
    python中的模块
    将python程序打包成exe
    python-执行过程
    python基础
  • 原文地址:https://www.cnblogs.com/BrainDeveloper/p/5373808.html
Copyright © 2011-2022 走看看