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

     使用场景:

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

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

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

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

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

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

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

    单例对象的创建方式:

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

  • 相关阅读:
    GitHub常用 库
    App性能优化
    iOS App性能优化
    UIButton图片与文字位置调整
    Mac常用目录
    js数字转金额,ajax调用接口,后台返回html(完整页面),打开新窗口并写入html
    js坑 把数字型的字符串默认为数字 把前面的0给去掉了("001")
    url跳转路径参数获取
    常用正则表达式,手机号,邮箱,网址
    Js获取操作系统版本 && 获得浏览器版本
  • 原文地址:https://www.cnblogs.com/dujq/p/7804442.html
Copyright © 2011-2022 走看看