文章出處
文章列表
namespace ObserverInNET { class Program { // 委托充當訂閱者接口類 public delegate void NotifyEventHandler(object sender); // 抽象訂閱號類 public class TenXun { public NotifyEventHandler NotifyEvent; public string Symbol { get; set; } public string Info { get; set; } public TenXun(string symbol, string info) { this.Symbol = symbol; this.Info = info; } #region 新增對訂閱號列表的維護操作 public void AddObserver(NotifyEventHandler ob) { NotifyEvent += ob; } public void RemoveObserver(NotifyEventHandler ob) { NotifyEvent -= ob; } #endregion public void Update() { if (NotifyEvent != null) { NotifyEvent(this); } } } // 具體訂閱號類 public class TenXunGame : TenXun { public TenXunGame(string symbol, string info) : base(symbol, info) { } } // 具體訂閱者類 public class Subscriber { public string Name { get; set; } public Subscriber(string name) { this.Name = name; } public void ReceiveAndPrint(Object obj) { TenXun tenxun = obj as TenXun; if (tenxun != null) { Console.WriteLine("Notified {0} of {1}'s" + " Info is: {2}", Name, tenxun.Symbol, tenxun.Info); } } } static void Main(string[] args) { TenXun tenXun = new TenXunGame("TenXun Game", "Have a new game published ...."); Subscriber lh = new Subscriber("Learning Hard"); Subscriber tom = new Subscriber("Tom"); // 添加訂閱者 tenXun.AddObserver(new NotifyEventHandler(lh.ReceiveAndPrint)); tenXun.AddObserver(new NotifyEventHandler(tom.ReceiveAndPrint)); tenXun.Update(); Console.WriteLine("-----------------------------------"); Console.WriteLine("移除Tom訂閱者"); tenXun.RemoveObserver(new NotifyEventHandler(tom.ReceiveAndPrint)); tenXun.Update(); Console.ReadLine(); } } }
文章列表
全站熱搜