结构 | |
意图 | 保证一个类仅有一个实例,并提供一个访问它的全局访问点。 |
适用性 |
|
1 using System; 2 3 class Singleton 4 { 5 private static Singleton _instance; 6 7 public static Singleton Instance() 8 { 9 if (_instance == null)10 _instance = new Singleton();11 return _instance;12 }13 protected Singleton(){}14 15 // Just to prove only a single instance exists16 private int x = 0;17 public void SetX(int newVal) {x = newVal;}18 public int GetX(){ return x;} 19 }20 21 ///22 /// Summary description for Client.23 /// 24 public class Client25 {26 public static int Main(string[] args)27 {28 int val;29 // can't call new, because constructor is protected30 Singleton FirstSingleton = Singleton.Instance(); 31 Singleton SecondSingleton = Singleton.Instance();32 33 // Now we have two variables, but both should refer to the same object34 // Let's prove this, by setting a value using one variable, and 35 // (hopefully!) retrieving the same value using the second variable36 FirstSingleton.SetX(4);37 Console.WriteLine("Using first variable for singleton, set x to 4"); 38 39 val = SecondSingleton.GetX();40 Console.WriteLine("Using second variable for singleton, value retrieved = {0}", val); 41 return 0;42 }43 }