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

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

 

    7.2.3 客户端代码


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

  Customer subject = new Customer();

  subject.Attach(new Accountant(subject));
  subject.Attach(new Cashier(subject));
  subject.Attach(new Dilliveryman(subject));

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

  Console.Read();
 }
 }

 


    运行结果:

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

 

  7.3 事件实现

    7.3.1 类图

C#,设计模式,观察者模式

    通过类图来看,观察者和主题之间已经不存在任何依赖关系了。

    7.3.2 代码实现


 /// <summary>
 /// 抽象主题
 /// </summary>
 public interface ISubject
 {
 void Notify();
 }

 /// <summary>
 /// 声明委托
 /// </summary>
 public delegate void CustomerEventHandler();

 /// <summary>
 /// 具体主题
 /// </summary>
 public class Customer : ISubject
 {
 private string customerState;

 // 声明一个委托事件,类型为 CustomerEventHandler
 public event CustomerEventHandler Update;

 public void Notify()
 {
  if (Update != null)
  {
  // 使用事件来通知给订阅者
  Update();
  }
 }

 public string CustomerState
 {
  get { return customerState; }
  set { customerState = value; }
 }
 }

 /// <summary>
 /// 财务,已经不需要实现抽象的观察者类,并且不用引用具体的主题
 /// </summary>
 public class Accountant
 {
 private string accountantState;

 public Accountant()
 { }

 /// <summary>
 /// 开发票
 /// </summary>
 public void GiveInvoice()
 {
  Console.WriteLine("我是会计,我来开具发票。");
  accountantState = "已开发票";
 }
 }

 /// <summary>
 /// 出纳,已经不需要实现抽象的观察者类,并且不用引用具体的主题
 /// </summary>
 public class Cashier
 {
 private string cashierState;

 public void Recoded()
 {
  Console.WriteLine("我是出纳员,我给登记入账。");
  cashierState = "已入账";
 }
 }

 /// <summary>
 /// 配送员,已经不需要实现抽象的观察者类,并且不用引用具体的主题
 /// </summary>
 public class Dilliveryman
 {
 private string dillivierymanState;

 public void Dilliver()
 {
  Console.WriteLine("我是配送员,我来发货。");
  dillivierymanState = "已发货";
 }
 }