设计模式面对面之单例模式

单例模式

类图:

常用的实现方式:

第一种线程安全

    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

 使用场景:

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

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

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

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

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

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

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

单例对象的创建方式:

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

posted @ 2017-11-08 18:05  杜俊强  阅读(152)  评论(0编辑  收藏  举报