• 观察者模式


    <?php

    class Newspaper implements SplSubject {
      private $name;
      private $observers;
      private $content;
      public function __construct($name){
        $this->$name = $name;
        $this->observers = new SplObjectStorage();
      }
      public function attach(SplObserver $observer){
        $this->observers->attach($observer);
      }
      public function detach(SplObserver $observer){
        $this->observers->detach($observer);
      }
      public function notify(){
        foreach ($this->observers as $observer) {
          $observer->update($this);
        }
      }
      public function getContent(){
        return $this->content."{$this->name}";
      }
      public function breakOutNews($content) {
        $this->content = $content;
        $this->notify();
      }
    }

    <?php

    class Reader implements SplObserver {
      private $name;
      public function __construct($name){
        $this->name = $name;
      }
      public function update(SplSubject $subject) {
        echo $this->name.' is reading breakout news'.$subject->getContent();
      }
    }

    <?php

    include "Newspaper.php";
    include "Reader.php";
    class WorkFlow {
      public function run() {
        $newspaper = new Newspaper('New York Times');
        $allen = new Reader("allen");
        $jimmy = new Reader("jimmy");
        $tom = new Reader("tom");
        $newspaper->attach($allen);
        $newspaper->attach($jimmy);
        $newspaper->attach($tom);
        $newspaper->detach($tom);
        $newspaper->breakOutNews('USA BREAK DOWN');

      }
    }
    $work = new WorkFlow();
    $work->run();

    newspaper是被观察的对象,reader是观察者。当报纸发布消息, 每一个用户都会得到通知。这就是观察者模式的使用场景。

  • 相关阅读:
    jquery swiper自定义pagination的方法
    javascript获取地址栏参数的方法
    jquery trigger使用方法
    jquery on绑定事件叠加解决方法
    phpexcel无法导出的解决方法
    mysql left join和union结合的用法
    Linux项目一
    排序
    搜索
    递归
  • 原文地址:https://www.cnblogs.com/liliuguang/p/13085926.html
Copyright © 2020-2023  润新知