设计模式——单键模式

名称 Singleton
结构  
意图 保证一个类仅有一个实例,并提供一个访问它的全局访问点。
适用性
  • 当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时。
  • 当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时。

 1// Singleton
 2
 3// Intent: "Ensure a class only has one instance, and provide a global
 4// point of access to it". 
 5
 6// For further information, read "Design Patterns", p127, Gamma et al.,
 7// Addison-Wesley, ISBN:0-201-63361-2
 8
 9/* Notes:
10 * If it makes sense to have only a single instance of a class (a so-called
11 * singleton), then it makes sense to enforce this (to elimintate potential 
12 * errors, etc). 
13 * 
14 * A class based on the singleton design pattern protects its constructor, 
15 * so that only the class itself (e.g. in a static method) may instantiate itself. 
16 * It exposes an Instance method which allows client code to retrieve the 
17 * current instance, and if it does not exist to instantiate it.  
18 */

19 
20namespace Singleton_DesignPattern
21{
22    using System;
23
24    class Singleton 
25    {
26        private static Singleton _instance;
27        
28        public static Singleton Instance()
29        {
30            if (_instance == null)
31                _instance = new Singleton();
32            return _instance;
33        }

34        protected Singleton(){}
35
36        // Just to prove only a single instance exists
37        private int x = 0;
38        public void SetX(int newVal) {x = newVal;}
39        public int GetX(){return x;}        
40    }

41
42    /// <summary>
43    ///    Summary description for Client.
44    /// </summary>

45    public class Client
46    {
47        public static int Main(string[] args)
48        {
49            int val;
50            // can't call new, because constructor is protected
51            Singleton FirstSingleton = Singleton.Instance(); 
52            Singleton SecondSingleton = Singleton.Instance();
53
54            // Now we have two variables, but both should refer to the same object
55            // Let's prove this, by setting a value using one variable, and 
56            // (hopefully!) retrieving the same value using the second variable
57            FirstSingleton.SetX(4);
58            Console.WriteLine("Using first variable for singleton, set x to 4");        
59
60            val = SecondSingleton.GetX();
61            Console.WriteLine("Using second variable for singleton, value retrieved = {0}", val);        
62            return 0;
63        }

64    }

65}

66
posted @ 2005-06-25 08:30  DarkAngel  阅读(1447)  评论(0编辑  收藏  举报