<?php
/*
*观察者模式:观察者设计模式能够更便利的创建和查看目标对象状态的对象,并且提供与核心对象非耦合的指定功能性
*/
class CD{
public $title = '';
public $band = "";
protected $_observers = array();
public function __construct( $title, $band) {
$this->title = $title;
$this->band = $band;
}
public function attachObserver( $type, $observer){
$this->_observers[$type][] = $observer;
}
public function notifyObserver($type){
if(isset ($this->_observers[$type])){
foreach($this->_observers[$type] as $observer){
$observer->update($this);
}
}
}
public function buy(){
$this->notifyObserver("purchased");
}
}
class buyCDNotifyStreamObserver{
public function update(CD $cd){
$activity = "The CD namde {$cd->title} by";
$activity.="{$cd->band} was just purchased";
activityStream::addNewItem( $activity);
}
}
class activityStream{
public static function addNewItem($item){
print $item;
}
}
$title = 'waste of a rib';
$band = 'never again';
$cd = new CD($tiltle, $band);
$observer = new buyCDNotifyStreamObserver();
$cd->attachObserver($type, $observer);
$cd->buy();
?>
/*
*观察者模式:观察者设计模式能够更便利的创建和查看目标对象状态的对象,并且提供与核心对象非耦合的指定功能性
*/
class CD{
public $title = '';
public $band = "";
protected $_observers = array();
public function __construct( $title, $band) {
$this->title = $title;
$this->band = $band;
}
public function attachObserver( $type, $observer){
$this->_observers[$type][] = $observer;
}
public function notifyObserver($type){
if(isset ($this->_observers[$type])){
foreach($this->_observers[$type] as $observer){
$observer->update($this);
}
}
}
public function buy(){
$this->notifyObserver("purchased");
}
}
class buyCDNotifyStreamObserver{
public function update(CD $cd){
$activity = "The CD namde {$cd->title} by";
$activity.="{$cd->band} was just purchased";
activityStream::addNewItem( $activity);
}
}
class activityStream{
public static function addNewItem($item){
print $item;
}
}
$title = 'waste of a rib';
$band = 'never again';
$cd = new CD($tiltle, $band);
$observer = new buyCDNotifyStreamObserver();
$cd->attachObserver($type, $observer);
$cd->buy();
?>