PHP 观察者模式的简单示例

前端之家收集整理的这篇文章主要介绍了PHP 观察者模式的简单示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
PHP观察者模式的实现方法,感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编来看看吧。
经测试代码如下:

<?PHP
/**
 * PHP观察者模式
 *
 * @param 
 * @author 编程之家 jb51.cc jb51.cc
 **/
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();
?>


/***   来自编程之家 jb51.cc(jb51.cc)   ***/
原文链接:https://www.f2er.com/php/529109.html

猜你在找的PHP相关文章