观察者模式PHP实现
2018-07-20 来源:open-open
<?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(); ?>
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐