现在的位置: 首页 > 综合 > 正文

php 观察者模式

2016年12月08日 ⁄ 综合 ⁄ 共 1146字 ⁄ 字号 评论关闭

观察者模式:

<?php
require_once("guanchazhe.php");

class BorderDecorator extends Widget{
	private $widget;
	
	function __construct(Widget $widget){
		$this->widget=$widget;
	}
	
	public function draw(){
		echo "<table border=0 cellpadding=1 bgcolor=#3366ff>";
		echo "<tr bgcolor=#ffffff><td>";
		$this->widget->draw();
		echo "</td></tr></table>";
	}
	
	public function update(Observable $subject){
		$this->widget->update($subject);		
	}
}

$widgetA=new BorderDecorator($widget);
$widgetA->draw();

?>

widget类的改写:

//观察者
interface Observer{
	public function update(Observable $subject);
}

abstract class Widget implements Observer{
	private $subject;
	abstract public function draw();
	public function update(Observable $subject){
		$this->subject=$subject;
	}
	public function getSubject(){
		return $this->subject;
	}
}

class BasicWidget extends Widget{
	function __construct(){
		
	}
	
	public function draw(){
		$html="<table border=1 width=130>";
		$html.="<tr><td colspan=3 bgcolor=#cccccc>" .
				"<b>Instrument Info<b></td></tr>";
		$data=$this->getSubject()->getData();
		$numRecords=count($data[0]);
		for($i=0;$i<$numRecords;$i++){
			$instms=$data[0];
			$prices=$data[1];
			$years=$data[2];
			$html.="<tr><td>$instms[$i]</td><td>$prices[$i]</td><td>$years[$i]</td></tr>";
		}
		$html.="</table><br>";
		echo $html;
	}
}

 

 

抱歉!评论已关闭.