zoukankan      html  css  js  c++  java
  • 设计模式面对面之单例模式

    单例模式

    类图:

    常用的实现方式:

    第一种线程安全

        public sealed class Singleton
        {
    
            public static readonly Singleton SingletonInstance=new Singleton();
    
            private Singleton()
            {
    
            }
        }
    View Code

     第二种单线程安全

     //第二种
        public sealed class SingletonLazy
        {
           
            private static SingletonLazy _singletonInstance;
    
            private SingletonLazy()
            {
    
            }
    
            //单线程,线程安全
            public static SingletonLazy SingletonInstance
            {
                get
                {
                    if (_singletonInstance == null)
                    {
                        _singletonInstance = new SingletonLazy();
                    }
    
                    return _singletonInstance;
                }
               
            }
    
        }
    View Code

    第三种线程安全

     public sealed class SingletonLazy
        {
           
            private static SingletonLazy _singletonInstance;
    
            private SingletonLazy()
            {
    
            }
    
            //多线程,线程安全
            private static readonly object AsyncObject = new object();
            public static SingletonLazy SingletonInstanceAsync
            {
                get
                {
                    if (_singletonInstance == null)
                    {
                        lock (AsyncObject)
                        {
                            if (_singletonInstance == null)
                            {
                                _singletonInstance = new SingletonLazy();
                            }
                        }
                        
                    }
    
                    return _singletonInstance;
                }
    
            }
        }
    View Code

     使用场景:

    当程序要求只有一个对象存在时,会考虑用单例模式。

    在使用前需要了解单例模式与静态对象区别:

     功能角度:二者可以相互替换,没什么区别,什么都不考虑的情况用那种方式都行。

     性能:单例对象可以延迟创建 ,优先考虑。

     扩展:单例对象可以实现多态,扩展性好,静态对象不能。

     线程安全:单例对象在多线程时,要考虑线程同步,静态对象不需要。

     在不考虑性能和扩展性的时候优先用静态对象。

    单例对象的创建方式:

    上面三种实现方式比较常见,当然实现方式很多,根据具体的场景去选择,一般默认第一种,简单方便。

  • 相关阅读:
    最大比例(压轴题 )
    HDU-1016-素数环
    HDU-1241-油藏
    POJ-2251-地下城
    UVa-12096-集合栈计算机
    UVa-156-反片语
    UVa-10815-安迪的第一个字典
    UVa-101-木块问题
    UVa-10474-大理石在哪
    HDU-2955-Robberies
  • 原文地址:https://www.cnblogs.com/dujq/p/7804442.html
Copyright © 2011-2022 走看看