您的位置:首页 > 其它

观察者模式:消息的发布与订阅

2012-01-08 12:33 525 查看
namespace YOObserver

{

class Program

{

static void Main(string[] args)

{

ClassOver co = new ClassOver();//下课

Teacher teacher = new Teacher("李老师", co);

Student student = new Student("小明同学",co);

co.Notify += new EventHandler(teacher.GoToOffice);

co.Notify += new EventHandler(student.GoToMess);

co.BellState = "下课铃响了";

Console.WriteLine("下课铃响了\n");

co.SendMessage();//将消息发出

Console.ReadKey();

}

}

//声明一个委托

delegate void EventHandler();

/// <summary>

/// 通知者,消息中心;铃声接口

/// </summary>

interface IBell

{

//响铃状态

string BellState { get; set; }

void SendMessage();

}

/// <summary>

/// 下课铃声

/// </summary>

class ClassOver : IBell

{

public event EventHandler Notify;

private string Msg;

#region IBell 成员

public string BellState

{

get

{

return Msg;

}

set

{

Msg = value;

}

}

public void SendMessage()

{

Notify();

}

#endregion

}

/// <summary>

/// 放学铃声

/// </summary>

class SchoolOver : IBell

{

public event EventHandler Notify;

private string Msg;

#region IBell 成员

public string BellState

{

get

{

return Msg;

}

set

{

Msg = value;

}

}

public void SendMessage()

{

Notify();

}

#endregion

}

/// <summary>

/// 教师

/// </summary>

class Teacher

{

//消息接收者

private string name;

private IBell iBell;

public Teacher(string name, IBell iBell)

{

this.name = name;

this.iBell = iBell;

}

public void GoToOffice()

{

Console.WriteLine("{0} 收到 {1} 消息后,去办公室",name,iBell.BellState);

}

}

/// <summary>

/// 学生

/// </summary>

class Student

{

//消息接收者

private string name;

private IBell iBell;

public Student(string name, IBell iBell)

{

this.name = name;

this.iBell = iBell;

}

public void GoToMess()

{

Console.WriteLine("{0} 收到 {1} 消息后,去食堂",name,iBell.BellState);

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: