龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > php编程 >

php 观察者模式PHP实现

时间:2017-10-24 11:01来源:网络整理 作者:网络 点击:
分享到:
观察者模式PHP实现 [代码片段(64行)]
<?php
interface Message {
   static function getType();
};

interface Observer {
   function notifyMsg(Message $msg);
};

class Subject {
   private $observers = Array();

   public function registerObserver(Observer $observer, $msgType) {
    $this->observers[$msgType][] = $observer;   // wyh?
   }

   private function notifyMsg(Message $msg) {
    @$observers = $this->observers[$msg->getType()];
    if (!$observers) {
     return;
    }

    foreach ($observers as $observer) {
     $observer->notifyMsg($msg);
    }
   }

   public function someMethod() {
           sleep(1);
          $this->notifyMsg(new HelloMessage("Michael"));
        }

}

class HelloMessage implements Message {
   private $name;

   public function __construct($name) {
    $this->name = $name;
   }

   public function getMsg() {
    return "Hello,$this->name!";
   }

   static function getType() {
    return "HELLO_TYPE";
   }
}

class SubObserver implements Observer {
   public function notifyMsg(Message $msg) {
    if ($msg instanceof HelloMessage) {
     echo $msg->getMsg();
    }
   }
}

$subject = new Subject();
    $observer = new SubObserver();
    $subject->registerObserver($observer, HelloMessage::getType());
    $subject->someMethod();

?>
精彩图集

赞助商链接