设计模式:单例

单例模式  Singleton Pattern

 

确保某一个类只有一个实例, 且自行实例化并向整个系统提供这个实例.

相信这个很多人都会,直接代码:

class Program
    {
        static void Main(string[] args)
        {
            Test t = Test.getInstance();
            Test t1 = Test.getInstance();
            if (t == t1)
            {
                Console.Write("一样的 ");
            }
            Console.ReadKey();
        }
        public class Test
        {
            public static Test t = null;
            //锁对象
            public readonly static object l = new Object();
            private Test()
            {
                //单例,执行一次构造函数
                Console.Write("------singleton---- ");
            }
            public static Test getInstance()
            {
                //加锁处理多并发问题
                lock (l)
                {
                    if (t == null)
                    {
                        t = new Test();
                        return t;
                    }
                    else
                    {
                        return t;
                    }
                }
            }
        }
    }

使用场合:

当在系统中某个特定的类对象实例只需要有一个的时候,可以使用单例设计模式,只有真正需要”单一实例”的时候才使用.

原文地址:https://www.cnblogs.com/Francis-YZR/p/4770972.html