设计模式-单例模式(Singleton Pattern)

来源:互联网 发布:受限的网络连接 编辑:程序博客网 时间:2024/05/01 08:05

单例模式的特点:

 单例类只能有一个实例

 单例类必须自己创建自己唯一的实例

单例类必须给所有其他对象提供这一实例


单例模式(Singleton Pattern )中只包含一个角色(Singleton),该角色拥有一个私有构造函数,确保

用户无法通过构造函数(new)去直接实例化。此外单例模式包含一个静态私有变量_Instance 以及静态共有方法CreateInstance().

CreateInstance方法负责检查并实例化自己,然后存储在静态变量_Instance 中,该过程中确保只有一个实力被创建。


代码:

public class Singleton
    {
        private static Singleton _Instance = null;


        /// <summary>
        /// 避免构造函数产生一个实例
        /// </summary>
        private Singleton() { }


        public static Singleton CreateInstance()
        {
            if(_Instance==null)
            {
                _Instance = new Singleton();
            }
            return _Instance;
        }


        public void Operate()
        {
            Console.WriteLine("this is the Operate method of Singleton");
        }


 class Program
    {
        static void Main(string[] args)
        {


            #region 单例模式


            Singleton instance = Singleton.CreateInstance();
            instance.Operate();
            return;
            #endregion


        }
    }


此外,考虑到单例模式可能会有多线程调用,采用以下方式。代码如下:

 public class Singleton2
    {
        private static readonly Singleton2 _Instance = new Singleton2();


        /// <summary>
        /// 避免构造函数产生一个实例
        /// </summary>
        private Singleton2() { }


        public static Singleton2 CreateInstance()
        {
            return _Instance;
        }


        public void Operate()
        {
            Console.WriteLine("this is the Operate method of Singleton2");
        }


    }


 

原创粉丝点击