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

Good Example Telling Event and Delegate

2010-03-26 00:30 363 查看
// from <Practical .Net2 and C#2 Harness the Platform , the language, the LFramework>

//Observer and Subscribers Pattern

using System;

class Subscriber{
private string m_name;
public Subscriber(string name){m_name=name;}

//Method to call whenan event is triggered
//i.d when a new report is published
public void OnReceivingInfo(object sender ,EventArgs e){
NewEventArgs info= e as NewEventArgs;
if info !=nulll {
Console.WriteLine(m_name +" receive the new: "+ ((NewEventArgs)e).GetBulletinInf());
}
}
}

//An instance of this class represents a new report
class NewEventArgs:EventArgs{
private stringm_Reprt;
public string GetBulletinInfo() {retrun m_Report;}
public NewsEventArgs(string report){m_Report=report;}
}

//The delegate class. Its instances reference subscriber methods.
public delegate void NewsEventHandler(object sender ,EventArgs e);

//The class whch publishes new reports by triggering events.
class NewsBoard{

//events used to publish news
public event NewsEventHandler USANews;
public event NewsEventHandler WorldNews;

//Methods used to trigger news publishing from outside NewsBoard.
public void OnUSANews(NewsEventArgs newReport){
if (USANews!=null)
USANews(this,newReport);
}
public void OnWorldNews(NewsEventArgs newReport){
if (WorldNews!=null)
WorldNews(this,NewReport);
}
}

class Proogram
{
public static void Main(){
NewsBoard newBord=new NewsBoard();

Subscriber bob=new Subcriber("Bob");
Subscriber joe=new Subcriber("Joe");
Subscriber Max=new Subcriber("Max");

//link Subscribers and the new board
newBoard.USANews +=bob.OnReceivingInfo;
newBoard.USANews +=joe.OnReceivingInfo;
newBoard.WordNews +=joe.OnReceivingInfo;
newBoard.WordNews +=max.OnReceivingInfo;

//public news reports by triggering events
newBoard.OnUSANews(new NewsEventArgs("Oil price increase."));
newBoard.OnWorldNews(new NewsEventArgs("New Election in France."));

//unsubscribe Joe.
newBoard.OnUSANews -= new NewsEventArgs(joe.OnReceivingInfo));

newBoard.OnUSANews(new NewsEventArgs("Hurricane alert."));

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