zoukankan      html  css  js  c++  java
  • 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."));
     
     }
    }

  • 相关阅读:
    2019.8.8 python day03
    2019.8.7 python进阶day02
    2019.8.6(python day01)
    2019.8.5
    2019.8.2
    2019.8.1
    2019.7.31
    2019.7.30
    面向对象进阶
    访问可见性问题和@property装饰器
  • 原文地址:https://www.cnblogs.com/no7dw/p/1696588.html
Copyright © 2011-2022 走看看