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

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

 

7. 下面例子分别用观察者模式,事件机制来实现

  7.1 实例描述:客户支付了订单款项,这时财务需要开具发票,出纳需要记账,配送员需要配货。

  7.2 观察者模式的实现

    7.2.1 类图

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

    7.2.2 代码实现


 /// <summary>
 /// 抽象观察者
 /// </summary>
 public interface ISubject
 {
 void Notify();
 }

 /// <summary>
 /// 工作岗位,作为这里的观察者的抽象
 /// </summary>
 public abstract class JobStation
 {
 public abstract void Update();
 }

 /// <summary>
 /// 具体主题,这里是客户
 /// </summary>
 public class Customer : ISubject
 {
 private string customerState;

 private IList<JobStation> observers = new List<JobStation>();

 /// <summary>
 /// 增加观察者
 /// </summary>
 /// <param name="observer"></param>
 public void Attach(JobStation observer)
 {
  this.observers.Add(observer);
 }

 /// <summary>
 /// 移除观察者
 /// </summary>
 /// <param name="observer"></param>
 public void Detach(JobStation observer)
 {
  this.observers.Remove(observer);
 }

 /// <summary>
 /// 客户状态
 /// </summary>
 public string CustomerState
 {
  get { return customerState; }
  set { customerState = value; }
 }

 public void Notify()
 {
  foreach (JobStation o in observers)
  {
  o.Update();
  }
 }
 }

 /// <summary>
 /// 会计
 /// </summary>
 public class Accountant : JobStation
 {
 private string accountantState;
 private Customer customer;

 public Accountant(Customer customer)
 {
  this.customer = customer;
 }

 /// <summary>
 /// 更新状态
 /// </summary>
 public override void Update()
 {
  if (customer.CustomerState == "已付款")
  {
  Console.WriteLine("我是会计,我来开具发票。");
  accountantState = "已开发票";
  }
 }
 }

 /// <summary>
 /// 出纳
 /// </summary>
 public class Cashier : JobStation
 {
 private string cashierState;
 private Customer customer;

 public Cashier(Customer customer)
 {
  this.customer = customer;
 }

 public override void Update()
 {
  if (customer.CustomerState == "已付款")
  {
  Console.WriteLine("我是出纳员,我给登记入账。");
  cashierState = "已入账";
  }
 }
 }

 /// <summary>
 /// 配送员
 /// </summary>
 public class Dilliveryman : JobStation
 {
 private string dillivierymanState;
 private Customer customer;

 public Dilliveryman(Customer customer)
 {
  this.customer = customer;
 }

 public override void Update()
 {
  if (customer.CustomerState == "已付款")
  {
  Console.WriteLine("我是配送员,我来发货。");
  dillivierymanState = "已发货";
  }
 }
 }