美文网首页
菜鸟带你看传说中的观察者模式!

菜鸟带你看传说中的观察者模式!

作者: 贱人配狗绝对天长地久 | 来源:发表于2018-07-05 22:25 被阅读4次
    <?php
    
    class Wechat
    {
        private $subscribers = array();
    
        public function register(Subscriber $subscriber)
        {
            $this->subscribers[] = $subscriber;
        }
    
        public function pushMessage($message)
        {
            foreach($this->subscribers as $subscriber)
            {
                $subscriber->getMessage($message);
            }
        }
    }
    
    interface Subscriber
    {
        public function getMessage($message);
    }
    
    class Evelin implements Subscriber
    {
        public function getMessage($message)
        {
            echo 'Evelin: '. $message;
        }
    }
    
    class Anke implements Subscriber
    {
        public function getMessage($message)
        {
            echo 'Anke: '. $message;
        }
    }
    
    $wechat = new Wechat();
    $evelin = new Evelin();
    $anke = new Anke();
    
    $wechat->register($evelin);
    $wechat->register($anke);
    $wechat->pushMessage('发新消息啦!');
    

    相关文章

      网友评论

          本文标题:菜鸟带你看传说中的观察者模式!

          本文链接:https://www.haomeiwen.com/subject/ygwtzttx.html