Singleton单件(创建型模式)

单件模式要求一个类有且仅有一个实例.
 Singleon类:
 1using System;
 2
 3namespace Singleton
 4{
 5    /// <summary>
 6    /// Singleton 的摘要说明。
 7    /// </summary>

 8    public class Singleton
 9    {
10     
11            private static Singleton _factory; 
12            private static Object _classLock = typeof(Singleton);
13            private long _wipMoves;
14            private Singleton()
15            {
16                _wipMoves = 0;
17            }

18            public static Singleton GetFactory()
19            {
20                lock (_classLock)
21                {
22                    if (_factory == null)
23                    {
24                        _factory = new Singleton();
25                    }

26                    return _factory;
27                }

28            }

29            public void RecordWipMove()
30            {
31                lock (_classLock)
32                {
33                    _wipMoves++;
34                }

35            }

36            // for the Aster star press example; not implemented
37            public void CollectPaste() 
38            {
39                Console.Write(_wipMoves+"\n");
40            }

41
42            /// <summary>
43            /// Return an example list of "up" machines, supporting "ShowConcurrentWhile"
44            /// and other examples).
45            /// </summary>
46            /// <returns>an example list of "up" machines</returns>

47             
48        }

49    }

50
51 
52

主程序:
 1using System;
 2
 3namespace Singleton
 4{
 5    /// <summary>
 6    /// Class1 的摘要说明。
 7    /// </summary>

 8    class Class1
 9    {
10        /// <summary>
11        /// 应用程序的主入口点。
12        /// </summary>

13        [STAThread]
14        static void Main(string[] args)
15        {
16            //
17            // TODO: 在此处添加代码以启动应用程序
18            //
19
20            Singleton singleton =Singleton.GetFactory();
21            singleton.RecordWipMove();
22            singleton.RecordWipMove();
23            
24            Singleton singleton1 =Singleton.GetFactory();
25            singleton1.RecordWipMove();
26            singleton1.RecordWipMove();
27        
28            singleton.CollectPaste();
29            singleton1.CollectPaste();
30            Console.WriteLine(object.ReferenceEquals(singleton, singleton1) == true);
31
32            Console.ReadLine();
33        }

34    }

35}

36
原文地址:https://www.cnblogs.com/walker/p/479663.html