C#事件委托、观察者模式、消息中心、消息转发

using System;namespace EventDelegation{ /// <summary> /// 事件参数类 /// </summary> public class EventDate : EventArgs { public int eventID; public int a; public int b; } /// <summary> /// 事件类,用于事件触发,消息转发,本质是消息中心,要使用单例模式 /// </summary> public class EventProgram { private static EventProgram _instance; public static EventProgram Instance { get { if(_instance == null) { _instance = new EventProgram(); } return _instance; } } public event EventHandler<EventDate> OnEvent; //事件触发函数 public void CallEvent(int eventID,int a,int b) { EventDate e = new EventDate(); //初始化事件参数 e.eventID = eventID; e.a = a; e.b = b; Console.WriteLine("CallEvent"); OnEvent(this, e); //触发调用 } } /// <summary> /// 事件处理类,观察者 /// </summary> class Observer { int _Id; public Observer(int id) { _Id = id; EventProgram.Instance.OnEvent += DoEvent; //订阅事件 } void DoEvent(System.Object sender, EventArgs e) { char f; int c = 0; EventDate ad = (EventDate)e; if(ad.eventID == 1) { c = ad.a + ad.b; f = ‘+‘; } else { c = ad.a - ad.b; f = ‘-‘; } Console.WriteLine("ID:"+_Id+ ",Observer触发事件DoEvent, a{1}b={0}", c,f); } } /// <summary> /// 事件处理类,观察者2 /// </summary> class Observer2 { int _Id; public Observer2(int id) { _Id = id; EventProgram.Instance.OnEvent += DoEvent2; //订阅事件 } void DoEvent2(System.Object sender, EventArgs e) { char f; int c = 0; EventDate ad = (EventDate)e; if (ad.eventID == 1) { c = ad.a * ad.b; f = ‘*‘; } else { c = ad.a / ad.b; f = ‘/‘; } Console.WriteLine("ID:" + _Id + ",Observer2触发事件DoEvent, a{1}b={0}", c, f); } } /// <summary> /// 事件触发者,被观察的对象 /// </summary> class EventTrigger { public void DoSomething() { EventProgram.Instance.CallEvent(1, 2, 3); //触发事件,通知消息中心 } } /// <summary> /// 测试 /// </summary> class Program { static void Main(string[] args) { //初始化各种观察者 Observer ob1 = new Observer(1); Observer ob2 = new Observer(2); Observer2 ob3 = new Observer2(1); Observer2 ob4 = new Observer2(2); //初始化事件触发者 EventTrigger et = new EventTrigger(); et.DoSomething(); Console.WriteLine("Hello World!"); } }}

  

相关文章