1. 程式人生 > >觀察者模式小示例

觀察者模式小示例

觀察 ade isset 消息 訂單狀態 ply 類名 htm clas

header("Content-type:text/html;charset=utf-8");
/**

  • 類名:Observer
  • 說明:觀察者模式
    */
    class Observer{
    // 聲明存放觀察者容器
    protected $container = array();

    /*

    • 新增觀察者函數
      */
      public function addObserver($type, $observer) {
      $this->container[$type][] = $observer;
      }

    /*

    • 運行訂單觀察者
      */
      public function runObserver($type,$obj) {
      if (isset($this->container[$type])) {
      foreach ($this->container[$type] as $obser) {
      $obj = new $obser();
      $obj->update($obj);
      }
      }
      }
      }

/**

  • 類名:Order
  • 說明:訂單類
  • 觀察者模式的使用
    */
    class Order {

    /*

    • 創建訂單
      */
      public function create($type,$observer) {
      echo ‘購買成功<br/>‘;
      $observer->runObserver($type,$this);
      }
      }

/*

  • 類名:Email
  • 說明:郵件類
    */
    class Email {
    public static function update($order) {
    echo ‘發送郵件<br/>‘;
    }
    }
    class Status {
    public static function update($order) {
    echo ‘改變訂單狀態<br/>‘;
    }
    }

$type1 = ‘buy‘;
$observer = new Observer();
$observer->addObServer($type1, ‘Email‘);
$observer->addObServer($type1, ‘Status‘);

$order = new Order();
$order->create($type1,$observer);

class Supply{

public function release($type,$observer){
echo "發布成功";
$observer->runObserver($type,$this);
}
}

class Sms{
public static function update($supply){
echo "推送消息";
}
}

$type2 = ‘release‘;
$observer2 = new Observer();
$observer2->addObserver($type2,‘Sms‘);

$supply = new Supply();
$supply->release($type2,$observer2);

觀察者模式小示例