[笔记]01Singleton 单件(创建型模式)

来源:互联网 发布:瑜伽网络课程 编辑:程序博客网 时间:2024/06/05 02:56



动机(Motivation)

一些特殊的类      只存在一个实例(确保他们的逻辑正确性)

这个应该是类设计者的责任,而不是使用者的责任。

如何绕过常规的构造器?提供一种机制保证一个类只有一个实例?


意图(Intent

确保一个类只有一个实例。


单线程Singleton模式实现

    class Singleton    {        private static Singleton instance;        private Singleton()        {        }        public static Singleton Instance        {            get            {                if(instance == null)                {                    instance = new Singleton();                }                return instance;            }        }    }

构造器可以设置为protected以允许子类派生

不要支持ICloneable接口

不要支持序列化

缺点是,不能应对多线程的情况

这个模式,我们只考虑了对象的创建而没有考虑对象的销毁


多线程实现

class MulThreadSingleton{    private static volatile MulThreadSingleton instance = null;    private static Object lockHelper = new Object();    private MulThreadSingleton()    {    }    public static MulThreadSingleton Instance    {        get        {            if(instance == null)            {                lock(lockHelper)                {                    if(instance == null)                    {                        instance = new MulThreadSingleton();                    }                }            }            return instance;        }    }}

使用静态构造器


    class StaticSingleton    {        public static readonly StaticSingleton Instance = new StaticSingleton();        private StaticSingleton()        {        }    }

以上代码等价于

    class Singleton    {        public static readonly Singleton Instance;        static Singleton()        {            Instance = new Singleton();        }        private Singleton()        {        }    }

静态构造器能保证,即使在多线程的环境下也只有一个线程访问到静态构造器

这样实现的缺点在于,在构造时没办法接收参数


Singleton模式扩展

这里提出几个关于Singleton模式扩展的几个思路

将一个实例扩展到N个实例


new构造器的调用转移到其他类中

 

理解和扩展Singleton模式的核心

如何控制用户使用new对一个类的实例构造器的任意调用