首页
学习
活动
专区
工具
TVP
发布

PHP观察者模式

//观察者模式

class Observer

{

  public $observers;

  public function setState()

  {

      $this->notifyAll();

  }

  private function notifyAll()

  {

      if(empty($this->observers))return null;

      foreach ($this->observers as $key => $value) {

          $className = $key;

          $funcName = $value;

          if (method_exists($className, $funcName))

          {

              call_user_func(array($className,$funcName));

          }

      }

  }

}

class BinaryObserver extends Observer

{

  public $subject;

  function __construct($subject)

  {

      $this->subject = $subject;

      $this->subject->observers['BinaryObserver'] = 'update';

  }

  protected function update()

  {

      echo "Binary String: ";

  }

}

class OctalObserver extends Observer

{

  public $subject;

  function __construct($subject)

  {

      $this->subject = $subject;

      $this->subject->observers['OctalObserver'] = 'update';

      //var_dump($this->subject->observers);

  }

  protected function update()

  {

      echo "Octal String: ";

  }

}

$subject = new Observer();

new BinaryObserver($subject);

new OctalObserver($subject);

$subject->setState();

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20210111A08VHA00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券