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

     使用场景:

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

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

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

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

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

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

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

    单例对象的创建方式:

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

  • 相关阅读:
    HYSBZ 3813 奇数国
    HYSBZ 4419 发微博
    HYSBZ 1079 着色方案
    HYSBZ 3506 排序机械臂
    HYSBZ 3224 Tyvj 1728 普通平衡树
    Unity 3D,地形属性
    nginx 的naginx 种包含include关键字
    Redis 出现NOAUTH Authentication required解决方案
    mysql 8.0出现 Public Key Retrieval is not allowed
    修改jar包里的源码时候需要注意的问题
  • 原文地址:https://www.cnblogs.com/dujq/p/7804442.html
Copyright © 2011-2022 走看看