C# 利用事件实现观察者模式

摘要本程序场景上下文如下:
有一个学校,由于这个学校的学风不太好,同学们和校警听到第三次铃声后,才分别走进教室和关闭学校大门。


代码如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace ConsoleApplication
 7 {
 8     /*
 9      * 本场景说明如下:
10      * 由于这个学校的学风不太好,同学们和校警听到第三次铃声后,才去做他们应该做的事。
11      **/
12     class Program
13     {
14         static void Main(string[] args)
15         {
16             var stu = new Student();
17             var plm = new Policeman();
18             var bel = new Bell();
19             bel.Name = "A-289";
20             bel.Ringing += new Bell.RingHandler(stu.OnTingRing);
21             bel.Ringing += new Bell.RingHandler(plm.OnTRing);
22 
23             bel.OnRinging(new RingEventArgs(3));
24         }
25     }
26     //观察者
27     class Student
28     {
29         public void OnTingRing(object sender, RingEventArgs e)
30         {
31             Console.WriteLine(string.Format("when student hearing the {0} ringing for {1} times,go to classroom", ((Bell)sender).Name, e.times));
32         }
33     }
34     //观察者
35     class Policeman
36     {
37         public void OnTRing(object sender, RingEventArgs e)
38         {
39             Console.WriteLine(string.Format("when school policeman hearing the {0} ringing for {1} times,close the school's gate", ((Bell)sender).Name, e.times));
40         }
41     }
42     //目标对象
43     class Bell
44     {
45         public delegate void RingHandler(object sender, RingEventArgs e);
46         public event RingHandler Ringing;
47         public string Name { getset; }
48 
49         public void OnRinging(RingEventArgs e)
50         {
51             if (Ringing != null)
52             {
53                 Ringing(this, e);
54             }
55         }
56     }
57 
58     class RingEventArgs : EventArgs
59     {
60         public RingEventArgs(int times)
61         {
62             this.times = times;
63         }
64         //次数
65         public int times { getset; }
66     }

67 }

 输出结果如下:

when student hearing the A-289 ringing for 3 times,go to classroom
when school policeman hearing the A-289 ringing for 3 times,close the school's gate
原文地址:https://www.cnblogs.com/cnbwang/p/2028731.html