Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
<?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是观察者。当报纸发布消息, 每一个用户都会得到通知。这就是观察者模式的使用场景。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...