观察者模式小示例
更新:HHH   时间:2023-1-7


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);



返回web开发教程...