• 技术文章 >php教程 >php手册

    Head First-观察者模式,headfirst-观察者

    2016-06-13 09:16:52原创1028

    Head First-观察者模式,headfirst-观察者


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

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

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

    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;
    	}
    }
    ?>
    

    我们在这些对象之间用松耦合的方式进行沟通,这样我们在后期维护的时候,可以大大的提高效率。

    设计原则:找出程序中会变化的方面,然后将其进行分离;针对接口编程,不针对实现编程;多用组合,少用继承

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:天气预报
    上一篇:PHP5全版本绕过open_basedir读文件脚本漏洞详细介绍, 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • PHP代码:Http断点续传的实现例子• PHP5中Cookie与 Session使用详解• php实现文件下载更能介绍• php写的简易聊天室代码• 整理:Apache+MySql+PHP的快速安装
    1/1

    PHP中文网