首页  >  问答  >  正文

php - 实际开发中哪些场景需要用到观察者模式?

实际开发中哪些场景需要用到观察者模式?能具体例子吗,最好有代码(PHP),谢谢!

ringa_leeringa_lee2720 天前415

全部回复(4)我来回复

  • 伊谢尔伦

    伊谢尔伦2017-04-11 10:30:44

    <?php
    /**
     * Created by PhpStorm.
     * User: zhudong
     * Date: 16/8/11
     * Time: 下午4:02
     */
    class Newspaper implements SplSubject {
        private $name;
        private $observers;
        private $content;
        public function __construct($name){
            $this->$name = $name;
            $this->observers = new SplObjectStorage();
        }
        public function attach(SplObserver $observer){
            $this->observers->attach($observer);
        }
        public function detach(SplObserver $observer){
            $this->observers->detach($observer);
        }
        public function notify(){
            foreach ($this->observers as $observer) {
                $observer->update($this);
            }
        }
        public function getContent(){
            return $this->content."{$this->name}";
        }
        public function breakOutNews($content) {
            $this->content = $content;
            $this->notify();
        }
    }
    
    <?php
    /**
     * Created by PhpStorm.
     * User: zhudong
     * Date: 16/8/11
     * Time: 下午4:17
     */
    class Reader implements SplObserver {
        private $name;
        public function __construct($name){
            $this->name = $name;
        }
        public function update(SplSubject $subject) {
            echo $this->name.' is reading breakout news'.$subject->getContent();
        }
    }
    
    <?php
    /**
     * Created by PhpStorm.
     * User: zhudong
     * Date: 16/8/11
     * Time: 下午4:26
     */
    include "Newspaper.php";
    include "Reader.php";
    class WorkFlow {
        public function run() {
            $newspaper = new Newspaper('New York Times');
            $allen = new Reader("allen");
            $jimmy = new Reader("jimmy");
            $tom = new Reader("tom");
            $newspaper->attach($allen);
            $newspaper->attach($jimmy);
            $newspaper->attach($tom);
            $newspaper->detach($tom);
            $newspaper->breakOutNews('USA BREAK DOWN');
            
        }
    }
    $work = new WorkFlow();
    $work->run();

    可以看这个例子,newspaper是被观察的对象,reader是观察者。当报纸发布消息, 每一个用户都会得到通知。这就是观察者模式的使用场景。

    回复
    0
  • 黄舟

    黄舟2017-04-11 10:30:44

    比如按業務來說的話,常見的就好比註冊、下訂單:

    • 註冊:一般會跟活動掛鉤,比如註冊送金幣、積分之類的;包括推薦人之類

    • 下訂單就比較多了,活動是最起碼的;其次比如發短信、郵件等

    以上是常見的場景。其實按到現實生活中的例子就是:警察來了,就得通知各個商販趕緊跑路。其中警察就是被觀察者,那些商販就是觀察者。

    回复
    0
  • 高洛峰

    高洛峰2017-04-11 10:30:44

    定义:当一个对象状态发生改变时,依赖他的对象全部得到通知
    优点:低耦合、非侵入式

    回复
    0
  • 黄舟

    黄舟2017-04-11 10:30:44

    laravel 事件

    回复
    0
  • 取消回复