首页 > 代码库 > php实现设计模式之 观察者模式

php实现设计模式之 观察者模式

代码片段一:

<?php /** * 观察者模式:定于对象间的一种一对多的依赖关系,当一个对象发生改变时,所有依赖它的对象都收到通知并自动更新。 *///例子:少林方丈的通讯录,当扫地僧的号码发生变化时,只需告诉方丈,方丈可通知自己通讯录里面的所有人interface Contacts{	public function addTel($tel);	public function delTel($tel);	public function notify();	public function action($action);}class StuContact implements Contacts{	public $contact;	public $action;	public function addTel($tel){		$this->contact[] = $tel;	}		public function delTel($tel){		$key = array_search($tel, $this->contact);		if($key !== FALSE){			unset($this->contact[$key]);		}else{			echo ‘通讯录中无此人‘;		}	}		public function notify(){		echo $this->action;		echo "<br/>";		foreach ($this->contact as $tel){			$tel->update();			echo "<br/>";		}	}		public function action($action){		$this->action = $action;	}}interface Tel{	public function update();}class StuTel implements Tel{	public $name;	public function __construct($name){		$this->name = $name;	}		public function update(){		echo $this->name.‘收到消息,已经更新‘;	}}class Client{	public static function main(){		$tel1 = new StuTel(‘虚竹‘);		$tel2 = new StuTel(‘乔峰‘);		$tel3 = new StuTel(‘段誉‘);				$contacts = new StuContact();		$contacts->addTel($tel1);		$contacts->addTel($tel2);		$contacts->addTel($tel3);				$contacts->action(‘扫地僧的号码更新了,是11111‘);		$contacts->notify();	}}Client::main();?>

  代码片段2

<?php/* * 观察者模式:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。 * 类型:行为类模式 *   *  *///抽象主题角色interface Subject{	public function Attach($Observer); //添加观察者	public function Detach($Observer); //踢出观察者	public function Notify(); //满足条件时通知观察者	public function SubjectState($Subject); //观察条件}//具体主题角色class Boss Implements Subject{	public $_action;	private $_Observer;	public function Attach($Observer)	{		$this->_Observer[] = $Observer;	}	public function Detach($Observer)	{		$ObserverKey = array_search($Observer, $this->_Observer);		if($ObserverKey !== false)		{			unset($this->_Observer[$ObserverKey]);		}	}	public function Notify()	{		foreach($this->_Observer as $value )		{			$value->Update();		}	}	public function SubjectState($Subject)	{		$this->_action = $Subject;	}}//抽象观察者角色abstract class Observer{	protected $_UserName;	protected $_Sub;	public function __construct($Name,$Sub)	{		$this->_UserName = $Name;		$this->_Sub = $Sub;	}	public abstract function Update(); //接收通过方法}//具体观察者角色class StockObserver extends Observer{	public function __construct($name,$sub)	{		parent::__construct($name,$sub);	}	public function Update()	{		echo $this->_Sub->_action.$this->_UserName." 你赶快跑...";	}}$huhansan = new Boss(); //被观察者$gongshil = new StockObserver("三毛",$huhansan); //初始化观察者$huhansan->Attach($gongshil); //添加一个观察者$huhansan->Attach($gongshil); //添加一个相同的观察者//$huhansan->Detach($gongshil); //踢出基中一个观察者$huhansan->SubjectState("警察来了"); //达到满足的条件$huhansan->Notify(); //通过所有有效的观察者?>

  UML类图如下

php实现设计模式之 观察者模式