观察者模式

什么是观察者模式?观察者模式定义了对象之间一对多的关系。

观察者模式中有主题(即可观察者)和观察者。主题用一个共同的接口来通知观察者,主题不知道观察者的细节,只知道观察者实现了主题的接口。

普遍的观察者模式中的推的方式更适合点,下面我们就写一个推的例子,天气站提供一个接口,当天气变化时,会将数据通知给各个看板显示。


<?php
//使用接口,类必须实现几个功能注册,删除,通知这几个动作
interface Subject{
    public function registerObserver(Observer $o);
    public function removeObserver(Observer $o);
    public function notifyObservers();
}
interface Observer{
    public function update($a,$b,$c);
}
//各个面板不同将改行为以接口实现
interface DisplayElement{
    public function display();
}
 
class Weather implements Subject{
    public $observers;
    public $changed=false;
    public $a;
    public $b;
    public $c;
 
    public function __construct(){
        $this->observers = array();
    }
    public function registerObserver(Observer $o){
        $this->observers[] = $o;
    }
    public function removeObserver(Observer $o){
        $key = array_search($o,$this->observers);
        if($key!==false){
            unset($this->observers[$key]);
        }
    }
    public function notifyObserver(){
        if($this->changed){
            foreach($this->observer as $ob){
                $ob->update($this->a,$this->b,$this->c);
            }
        }
    }
    public function setChanged(){
        $this->changed = true;
    }
    //当数值改变时通知各个观察者
    public function measurementsChanged(){
        $this->setChanged();
        $this->notifyObserver();
    }
 
    public function setMeasurements($a,$b,$c){
        $this->a = $a;
        $this->b = $b;
        $this->c = $c;
        $this->measurementsChanged();       
    }
}
 
class CurrentConditionsDisplay implements Observer, DisplayElement{
    public $a;
    public $b;
    public $c;
    public $subject;
 
    public function __construct(Subject $weather){
        $this->subject = $weather;
        $this->subject->registerObserver($this);
    }
 
    public function update($a,$b,$c){
        $this->a = $a;
        $this->b = $b;
        $this->c = $c;
        $this->display();
    }
 
    public function display(){
        echo $this->a.$this->b.$this->c;
    }
}
?>

转载:如侵权:联系删除

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值