单件模式 Singleton---Design Pattern 5

单件模式 Singleton

单件模式:确保一个类只有一个实例,并提供一个全局访问点

    //包含单件实例的类Singleton
    public class Singleton
    {
        //声明用于存储单件实例的变量instance
        private static Singleton instance;
        //定义用于标识同步线程的对象locker
        private static Object locker = new Object();
        //私有的构造函数Singleton
        private Singleton() { }
        //公共访问的返回单件实例的函数GetInstance
        public static Singleton GetInstance()
        {
            //第一重“锁”只为了提高些性能
            if (instance == null)
            {
                //线程锁定块
                lock (locker)
                {
                    //第二重“锁”防止多线程多次new实例
                    if (instance == null)
                    {
                        //new唯一实例
                        instance = new Singleton();
                    }
                }
            }
            //返回单件实例
            return instance;
        }
    }
    //程序调用入口(Main方法)
    class Program
    {
        static void Main(string[] args)
        {
            Singleton s1 = Singleton.GetInstance();
            Singleton s2 = Singleton.GetInstance();
            if (s1 == s2)   //True
            {
                Console.WriteLine("Objects are the same instance!");
            }
            Console.ReadKey();
        }
    }

当我们的系统中某个对象只需要一个实例的情况,例如:操作系统中只能有一个任务管理器,操作文件时,同一时间内只允许一个实例对其操作等时可以用此模式。

原文地址:https://www.cnblogs.com/wangweiabcd/p/3900659.html