zoukankan      html  css  js  c++  java
  • 观察者模式

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

  • 相关阅读:
    《Vue.js 2.x实践指南》 已出版
    《H5+移动应用实战开发》已出版
    关于《ASP.NET MVC企业级实战》
    ASP.NET MVC企业级实战目录
    ASP.NET MVC4入门到精通系列目录汇总
    网站服务架构
    ASP.NET MVC搭建项目后台UI框架—1、后台主框架
    webpack介绍—上
    通过一个vue+elementUI的小实例来讲解一下它们是如何使用的
    不要为自己学历低找借口
  • 原文地址:https://www.cnblogs.com/liliuguang/p/13085926.html
Copyright © 2011-2022 走看看