using System; using System.Collections.Generic; using System.Text; ///Singleton(单件)模式用于保证一个类仅有一个实例,并提供一个访问该实例的全局访问点。 ///add by jzh 2007-04-15 namespace DesignPattern { class Singleton { private static Singleton _instance; public static Singleton Instance() { if (_instance == null) _instance = new Singleton(); return _instance; } protected Singleton() { } private int x = 0; public void SetX(int newVal) { x = newVal; } public int GetX() { return x; } } public class Client { public static void Main(string[] args) { int val; Singleton FirstSingleton = Singleton.Instance(); Singleton SecondSingleton = Singleton.Instance(); // 重新得到 FirstSingleton.SetX(4); Console.WriteLine("赋值, set x to 4"); val = SecondSingleton.GetX(); Console.WriteLine("取值, value retrieved = {0}", val); Console.ReadLine(); } } }