Observer设计模式主要包括以下两种对象:
(1)被观察对象:Subject,它往往包含其他对象感兴趣的东西,上面例子中热水器中就是Subject(被监视对象);
(2)观察对象:Observer,它观察着Subject,当Subject中的某件事发生后,会告知Observer,Obersver会采取相应的行动。上面例子中显示器和报警器就是观察对象,当油箱中温度大于95°时,报警器和显示器就会做出相应的警报;
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ObserverApp { class Program { static void Main(string[] args) { Oil o = new Oil(); o.BoiledEvent += new Alarm().MakeAlarm;//先往Oil对象中注册事件 o.BoiledEvent += new Display().ShowMsg;//先往Oil对象中注册事件 o.BoilWater();//执行主要方法,等到条件合适在触发上面注册的事件 } } /// <summary> /// Subject被观察对象 ---Oil热水器 /// </summary> internal class Oil { /// <summary> /// 牌子 /// </summary> public string brand = "Nick"; /// <summary> /// 价格 /// </summary> public int price = 1000; public delegate void BoiledHandler(object obj, EventArgs args); public event BoiledHandler BoiledEvent; /// <summary> /// 将观察者感兴趣的信息通过实例传递过去 /// </summary> public class BoilEventArgs : EventArgs { public int Temperature { get; set; } public BoilEventArgs(int temperature) { this.Temperature = temperature; } } public void BoilWater() { for (int i = 0; i <= 100; i++) { if (i >= 95) { BoilEventArgs args = new BoilEventArgs(i); BoiledEvent(this, args);//当温度达到95度及以上的时候,触发所有订阅该事件的观察者的方法 } } } } /// <summary> /// Observer观察对象 ---警报器 /// </summary> internal class Alarm { public void MakeAlarm(object sender,EventArgs args) { Oil o = (Oil)sender; ObserverApp.Oil.BoilEventArgs a = (ObserverApp.Oil.BoilEventArgs)args; Console.WriteLine("Alarm:嘀嘀嘀,水已经 {0} 度了,当前热水器的牌子是{1},价格是{2}",a.Temperature, o.brand, o.price); } } /// <summary> /// Observer观察对象 ---显示器 /// </summary> internal class Display { public void ShowMsg(object sender, EventArgs args) { Oil o = (Oil)sender; ObserverApp.Oil.BoilEventArgs a = (ObserverApp.Oil.BoilEventArgs)args; Console.WriteLine("Display:水已烧开,当前温度:{0}度,当前热水器的牌子是{1},价格是{2}", a.Temperature, o.brand, o.price); Console.ReadKey(); } } }