using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyOb { public delegate void ObserverDelegate<T>(T e); public class Observer<T> { // 利用委託對象作爲 觀察者列表 //函數指針 private ObserverDelegate<T> observerList; //事件 //註冊或移除觀察者 public event ObserverDelegate<T> Observers { add //註冊觀察者 { //指針增長綁定函數 observerList += value; } remove//移除觀察者 { observerList -= value; } } protected virtual void OnHandler(T e) { if (observerList != null) observerList(e); } //通知全部觀察者 主題的狀態發生改變 protected void Notify(T e) { OnHandler(e); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyOb { interface ICommand { void Execute(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyOb { public class Sample4 : ICommand { protected class WaterMessage { public readonly Heater Heater; public readonly int Temperature; public WaterMessage(Heater heater, int temperature) { this.Heater = heater; this.Temperature = temperature; } } protected class Heater : Observer<WaterMessage> { public string Type = "001"; // 添加型號做爲演示 public string Area = "China"; // 添加產地做爲演示 public void BoildWater() { for (int temperature = 0; temperature <= 100; temperature++) { if (temperature > 98) { Notify(new WaterMessage(this, temperature)); } } } } public void Execute() { // 主題對象 - 熱水器 Heater heater = new Heater(); //註冊觀察者 - 警報器 ,事件綁定函數 heater.Observers += MakeAlert; //註冊觀察者 - 顯示器 ,事件綁定函數 heater.Observers += ShowMsg; heater.BoildWater(); Lighter lighter = new Lighter(); //張三進屋看到了一個大燈 lighter.Observers += ZhangSan; //李四進屋看到了一個大燈 lighter.Observers += LiSi; lighter.Opened = true; lighter.Opened = false; lighter.Opened = true; } //如今的消息處理函數但是泛型的了呀,不須要類型轉化了 private void MakeAlert(WaterMessage m) { Console.WriteLine("Alarm:{0} - {1}: ", m.Heater.Area, m.Heater.Type); Console.WriteLine("Alarm: 嘀嘀嘀,水已經 {0} 度了:", m.Temperature.ToString()); Console.WriteLine(); } //如今的消息處理函數但是泛型的了呀,不須要類型轉化了 private void ShowMsg(WaterMessage m) { Console.WriteLine("Display:{0} - {1}: ", m.Heater.Area, m.Heater.Type); Console.WriteLine("Display:水快燒開了,當前溫度:{0}度。", m.Temperature.ToString()); Console.WriteLine(); } private void Response(string person, bool opened) { if (opened) { Console.WriteLine("{0} 激動地喊【奧,來電了!】", person); } else { Console.WriteLine("{0} 嘆氣的說【孃的,又停電了!】", person); } } public void ZhangSan(bool e) { Response("ZhangSan", (bool)e); } public void LiSi(bool e) { Response("LiSi", e); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyOb { class Lighter : Observer<bool> { private bool opened = false; public bool Opened { get { return opened; } set { if (opened != value) { opened = value; Notify(value); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyOb { class Program { static void Main(string[] args) { ICommand sample = new Sample4(); sample.Execute(); Console.ReadLine(); } } }