Good Example Telling Event and Delegate

// 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."));
 
 }
}

 

 

posted @ 2010-03-26 00:30  邓维  阅读(182)  评论(0编辑  收藏  举报