C# 设计模式系列教程-观察者模式

2019-12-30 12:40:04刘景俊

 

    7.3.3 客户端代码


 class Program
 {
 static void Main(string[] args)
 {

  Customer subject = new Customer();

  Accountant accountant = new Accountant();
  Cashier cashier = new Cashier();
  Dilliveryman dilliveryman = new Dilliveryman();

  // 注册事件
  subject.Update += accountant.GiveInvoice;
  subject.Update += cashier.Recoded;
  subject.Update += dilliveryman.Dilliver;

  /*
  * 以上写法也可以用下面代码来替换
  subject.Update += new CustomerEventHandler(accountant.GiveInvoice);
  subject.Update += new CustomerEventHandler(cashier.Recoded);
  subject.Update += new CustomerEventHandler(dilliveryman.Dilliver);
  */

  subject.CustomerState = "已付款";
  subject.Notify();

  Console.Read();
 }
 }


    运行结果

    我是会计,我来开具发票。
    我是出纳员,我给登记入账。
    我是配送员,我来发货。



注:相关教程知识阅读请移步到c#教程频道。