小狗、小偷、主人的事件设计
故事简介:在一个漆黑的夜晚,小偷潜入一间民宅,机警的小狗发现小偷,于是发出汪汪的示警声。小偷听到小狗的示警声,被吓跑了,主人听到了小狗的示警声,被惊醒了。
/// <summary> /// 小狗 /// </summary> class Dog { public event EventHandler BarkEvent;// 狗叫事件 public void Bark() { Console.WriteLine("小狗:汪汪,小偷来了"); OnBark(new EventArgs()); } protected virtual void OnBark(EventArgs e) { EventHandler handler = BarkEvent; if (handler != null) { handler.Invoke(this, e); } } } /// <summary> /// 小偷 /// </summary> class Thief { public Thief(Dog dog) { dog.BarkEvent += new EventHandler(dog_BarkEvent);//小偷订阅小狗的狗叫事件 } void dog_BarkEvent(object sender, EventArgs e) { Console.WriteLine("小偷:狗叫了,我要跑路了"); } } /// <summary> /// 主人 /// </summary> class Master { public Master(Dog dog) { dog.BarkEvent += new EventHandler(dog_BarkEvent);//主人订阅小狗的狗叫事件 } void dog_BarkEvent(object sender, EventArgs e) { Console.WriteLine("主人:狗叫了,把我给吵醒来了"); } } class Program { static void Main(string[] args) { Dog dog = new Dog(); Thief thief = new Thief(dog); Master master = new Master(dog); dog.Bark(); Console.ReadLine(); } }