<?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是观察者。当报纸发布消息, 每一个用户都会得到通知。这就是观察者模式的使用场景。

posted on 2020-06-10 16:10  李留广  阅读(131)  评论(0编辑  收藏  举报