Home > php教程 > PHP源码 > PHP实现观察者模式

PHP实现观察者模式

PHP中文网
Release: 2016-05-25 17:14:37
Original
900 people have browsed it

PHP实现观察者模式

<?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();

?>
Copy after login


以上就是PHP实现观察者模式的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template