观察者模式 类图
Suject.php
<?php
/**
* @Author: Cizel
* @Date: 2016-04-07 16:49:03
* @Last Modified by: Cizel
* @Last Modified time: 2016-04-07 18:10:15
*/
interface Subject{
public function addObserver($observer);
public function deleteObserver($observer);
public function notifyObserver();
}
ConcreteSubject.php
<?php
/**
* @Author: Cizel
* @Date: 2016-04-07 16:54:35
* @Last Modified by: Cizel
* @Last Modified time: 2016-04-07 18:37:12
*/
class ConcreteSubject implements Subject{
private $observerList;
public function __construct(){
$this->observerList = null;
}
public function getObserverList(){
return $this->observerList;
}
public function addObserver($observer){
if($this->observerList==null || in_array($observer, $this->observerList,true) == false){
$this->observerList[] = $observer;
}
}
public function deleteObserver($observer){
if(($key = array_search($observer,$this->observerList)) !==false){
unset($this->observerList[$key]);
}
}
public function notifyObserver(){
foreach ($this->observerList as $key => $value) {
$value->update();
}
}
}
Observer.php
<?php
/**
* @Author: Cizel
* @Date: 2016-04-07 17:07:13
* @Last Modified by: Cizel
* @Last Modified time: 2016-04-07 17:42:15
*/
interface Observer{
public function update();
}
ConcreteObserver.php
<?php
/**
* @Author: Cizel
* @Date: 2016-04-07 17:09:03
* @Last Modified by: Cizel
* @Last Modified time: 2016-04-07 18:14:30
*/
class ConcreteObserver implements Observer{
public function update(){
echo "res update <br />";
}
}
index.php 入口文件
<?php
/**
* @Author: Cizel
* @Date: 2016-04-07 17:10:54
* @Last Modified by: Cizel
* @Last Modified time: 2016-04-07 18:27:34
*/
function __autoload($classname) {
require_once($classname.".php");
}
$center = new ConcreteSubject();
$observer1 = new ConcreteObserver();
$observer2 = new ConcreteObserver();
$center->addObserver($observer1);
$center->addObserver($observer2);
$center->notifyObserver();
echo "delete 1 <br />";
$center->deleteObserver($observer2);
$center->notifyObserver();
笔者在校期间都是使用强类型的语言C++/Java等去实现算法和数据结构,现在写php感到很是不习惯。感觉php类面向对象,调试程序的时候非常麻烦。不知道xdebug可不可以解决这个问题。