Suject.phpphp
<?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.phpui
<?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 入口文件this
<?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可不能夠解決這個問題。spa