您的位置:首页 > 编程语言 > C#

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

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

代码如下:

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace ConsoleApplication
7 {
8 /*
9 * 本场景说明如下:
* 由于这个学校的学风不太好,同学们和校警听到第三次铃声后,才去做他们应该做的事。
**/
class Program
{
static void Main(string[] args)
{
var stu = new Student();
var plm = new Policeman();
var bel = new Bell();
bel.Name = "A-289";
bel.Ringing += new Bell.RingHandler(stu.OnTingRing);
bel.Ringing += new Bell.RingHandler(plm.OnTRing);

bel.OnRinging(new RingEventArgs(3));
}
}
//观察者
class Student
{
public void OnTingRing(object sender, RingEventArgs e)
{
Console.WriteLine(string.Format("when student hearing the {0} ringing for {1} times,go to classroom", ((Bell)sender).Name, e.times));
}
}
//观察者
class Policeman
{
public void OnTRing(object sender, RingEventArgs e)
{
Console.WriteLine(string.Format("when school policeman hearing the {0} ringing for {1} times,close the school's gate", ((Bell)sender).Name, e.times));
}
}
//目标对象
class Bell
{
public delegate void RingHandler(object sender, RingEventArgs e);
public event RingHandler Ringing;
public string Name { get; set; }

public void OnRinging(RingEventArgs e)
{
if (Ringing != null)
{
Ringing(this, e);
}
}
}

class RingEventArgs : EventArgs
{
public RingEventArgs(int times)
{
this.times = times;
}
//次数
public int times { get; set; }
} }

输出结果如下:

when student hearing the A-289 ringing for 3 times,go to classroomwhen school policeman hearing the A-289 ringing for 3 times,close the school's gate
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: