├── prototype └── prototype.php ├── template_method └── template_method.php ├── singleton └── mysql_singleton.php ├── factory_method └── factory_method.php ├── abstract_factory └── abstract_factory.php ├── proxy └── proxy.php ├── README.md ├── responsibility_chain └── responsibility_chain.php ├── command └── command.php ├── bridge └── bridge.php ├── adapter └── adapter.php ├── strategy └── strategy.php ├── flyweight └── flyweight.php ├── interpreter └── interpreter.php ├── decorator └── decorator.php ├── mediator └── mediator.php ├── state └── state.php ├── memento └── memento.php ├── observer └── observer.php ├── facade └── facade.php ├── visitor └── visitor.php ├── iteration └── iteration.php └── composite └── composite.php /prototype/prototype.php: -------------------------------------------------------------------------------- 1 | _name = $name; } 8 | public function copy() { return clone $this;} 9 | } 10 | 11 | class Demo {} 12 | 13 | // client 14 | 15 | $demo = new Demo(); 16 | $object1 = new ConcretePrototype($demo); 17 | $object2 = $object1->copy(); 18 | ?> -------------------------------------------------------------------------------- /template_method/template_method.php: -------------------------------------------------------------------------------- 1 | primitiveOperation1(); 5 | $this->primitiveOperation2(); 6 | } 7 | abstract protected function primitiveOperation1(); // 基本方法 8 | abstract protected function primitiveOperation2(); 9 | } 10 | 11 | class ConcreteClass extends AbstractClass { // 具体模板角色 12 | protected function primitiveOperation1() {} 13 | protected function primitiveOperation2(){} 14 | 15 | } 16 | 17 | $class = new ConcreteClass(); 18 | $class->templateMethod(); 19 | ?> -------------------------------------------------------------------------------- /singleton/mysql_singleton.php: -------------------------------------------------------------------------------- 1 | conn = mysql_connect('localhost','root',''); 9 | } 10 | 11 | //创建一个用来实例化对象的方法 12 | public static function getInstance(){ 13 | if(!(self::$conn instanceof self)){ 14 | self::$conn = new self; 15 | } 16 | return self::$conn; 17 | } 18 | 19 | //防止对象被复制 20 | public function __clone(){ 21 | trigger_error('Clone is not allowed !'); 22 | } 23 | 24 | } 25 | 26 | //只能这样取得实例,不能new 和 clone 27 | $mysql = Mysql::getInstance(); 28 | ?> -------------------------------------------------------------------------------- /factory_method/factory_method.php: -------------------------------------------------------------------------------- 1 | createButton('Mac')); 26 | var_dump($button_obj->createButton('Win')); 27 | ?> -------------------------------------------------------------------------------- /abstract_factory/abstract_factory.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /proxy/proxy.php: -------------------------------------------------------------------------------- 1 | _beforeAction(); 17 | if (is_null($this->_real_subject)) { 18 | $this->_real_subject = new RealSubject(); 19 | } 20 | $this->_real_subject->action(); 21 | $this->_afterAction(); 22 | } 23 | 24 | private function _beforeAction() { 25 | echo '在action前,我想干点啥....'; 26 | } 27 | 28 | private function _afterAction() { 29 | echo '在action后,我还想干点啥....'; 30 | } 31 | } 32 | 33 | // client 34 | $subject = new ProxySubject(); 35 | $subject->action(); 36 | 37 | ?> -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Php_Design_Patterns # 2 | 学习理解设计模式,记录PHP关于23种设计模式的使用,欢迎star 3 | 4 | 设计模式分为:创建型模式, 结构型模式,行为型模式等23种设计模式。 5 | 6 | ### 一、五种创建型模式如下: 7 | 工厂方法模式factory_method 8 | 抽象工厂模式abstract_factory 9 | 单例模式singleton 10 | 建造者模式builder 11 | 原型模式prototype 12 | 13 | ### 二、结构型模式如下: 14 | 适配器模式adapter 15 | 桥接模式bridge 16 | 合成模式composite 17 | 装饰器模式decorator 18 | 门面模式facade 19 | 代理模式proxy 20 | 享元模式flyweight 21 | 22 | ### 三、行为型模式如下: 23 | 策略模式strategy 24 | 模板方法模式template_method 25 | 观察者模式observer 26 | 迭代器模式decorator 27 | 责任链模式responsibility_chain 28 | 命令模式command 29 | 备忘录模式memento 30 | 状态模式state 31 | 访问者模式visitor 32 | 中介者模式mediator 33 | 解释器模式interpreter 34 | 35 | ### 设计模式六大原则: 36 | 开放封闭原则:一个软件实体如类、模块和函数应该对扩展开放,对修改关闭。 37 | 里氏替换原则:所有引用基类的地方必须能透明地使用其子类的对象. 38 | 依赖倒置原则:高层模块不应该依赖低层模块,二者都应该依赖其抽象;抽象不应该依赖细节;细节应该依赖抽象。 39 | 单一职责原则:不要存在多于一个导致类变更的原因。通俗的说,即一个类只负责一项职责。 40 | 接口隔离原则:客户端不应该依赖它不需要的接口;一个类对另一个类的依赖应该建立在最小的接口上。 41 | 迪米特法则:一个对象应该对其他对象保持最少的了解。 -------------------------------------------------------------------------------- /responsibility_chain/responsibility_chain.php: -------------------------------------------------------------------------------- 1 | next = $l; 8 | return $this; 9 | } 10 | abstract public function operate(); // 操作方法 11 | } 12 | 13 | class ResponsibilityA extends Responsibility { 14 | public function __construct() {} 15 | public function operate(){ 16 | if (false == is_null($this->next)) { 17 | $this->next->operate(); 18 | echo 'Res_A start'."
"; 19 | } 20 | } 21 | } 22 | 23 | class ResponsibilityB extends Responsibility { 24 | public function __construct() {} 25 | public function operate(){ 26 | if (false == is_null($this->next)) { 27 | $this->next->operate(); 28 | echo 'Res_B start'; 29 | } 30 | } 31 | } 32 | 33 | $res_a = new ResponsibilityA(); 34 | $res_b = new ResponsibilityB(); 35 | $res_a->setNext($res_b); 36 | $res_a->operate(); 37 | ?> -------------------------------------------------------------------------------- /command/command.php: -------------------------------------------------------------------------------- 1 | _receiver = $receiver; 10 | } 11 | public function execute() { 12 | $this->_receiver->action(); 13 | } 14 | } 15 | 16 | class Receiver { // 接收者角色 17 | private $_name; 18 | public function __construct($name) { 19 | $this->_name = $name; 20 | } 21 | public function action() { 22 | echo 'receive some cmd:'.$this->_name; 23 | } 24 | } 25 | 26 | class Invoker { // 请求者角色 27 | private $_command; 28 | public function __construct(Command $command) { 29 | $this->_command = $command; 30 | } 31 | public function action() { 32 | $this->_command->execute(); 33 | } 34 | } 35 | 36 | $receiver = new Receiver('hello world'); 37 | $command = new ConcreteCommand($receiver); 38 | $invoker = new Invoker($command); 39 | $invoker->action(); 40 | ?> -------------------------------------------------------------------------------- /bridge/bridge.php: -------------------------------------------------------------------------------- 1 | imp->operationImp(); 6 | } 7 | } 8 | 9 | class RefinedAbstraction extends Abstraction { // 修正抽象化角色, 扩展抽象化角色,改变和修正父类对抽象化的定义。 10 | public function __construct(Implementor $imp) { 11 | $this->imp = $imp; 12 | } 13 | public function operation() { $this->imp->operationImp(); } 14 | } 15 | 16 | abstract class Implementor { // 实现化角色, 给出实现化角色的接口,但不给出具体的实现。 17 | abstract public function operationImp(); 18 | } 19 | 20 | class ConcreteImplementorA extends Implementor { // 具体化角色A 21 | public function operationImp() {} 22 | } 23 | 24 | class ConcreteImplementorB extends Implementor { // 具体化角色B 25 | public function operationImp() {} 26 | } 27 | 28 | // client 29 | $abstraction = new RefinedAbstraction(new ConcreteImplementorA()); 30 | $abstraction->operation(); 31 | 32 | $abstraction = new RefinedAbstraction(new ConcreteImplementorB()); 33 | $abstraction->operation(); 34 | ?> -------------------------------------------------------------------------------- /adapter/adapter.php: -------------------------------------------------------------------------------- 1 | _adaptee = $adaptee; 20 | } 21 | 22 | public function sampleMethod1() { 23 | $this->_adaptee->sampleMethod1(); 24 | } 25 | 26 | public function sampleMethod2() { 27 | echo '!!!!!!!!'; 28 | } 29 | } 30 | 31 | 32 | $adapter = new Adapter(new Adaptee()); 33 | $adapter->sampleMethod1(); 34 | $adapter->sampleMethod2(); 35 | 36 | 37 | //类适配器 38 | interface Target2 { 39 | public function sampleMethod1(); 40 | public function sampleMethod2(); 41 | } 42 | 43 | class Adaptee2 { // 源角色 44 | public function sampleMethod1() {} 45 | } 46 | 47 | class Adapter2 extends Adaptee2 implements Target2 { // 适配后角色 48 | public function sampleMethod2() {} 49 | } 50 | 51 | $adapter = new Adapter2(); 52 | $adapter->sampleMethod1(); 53 | $adapter->sampleMethod2(); 54 | ?> -------------------------------------------------------------------------------- /strategy/strategy.php: -------------------------------------------------------------------------------- 1 | _strategy = $strategy; 30 | } 31 | public function handle_question() { 32 | $this->_strategy->do_method(); 33 | } 34 | } 35 | 36 | // client 37 | $strategyA = new ConcreteStrategyA(); 38 | $question = new Question($strategyA); 39 | $question->handle_question(); 40 | 41 | $strategyB = new ConcreteStrategyB(); 42 | $question = new Question($strategyB); 43 | $question->handle_question(); 44 | 45 | $strategyC = new ConcreteStrategyC(); 46 | $question = new Question($strategyC); 47 | $question->handle_question(); 48 | ?> -------------------------------------------------------------------------------- /flyweight/flyweight.php: -------------------------------------------------------------------------------- 1 | resource = $resource_str; 11 | } 12 | 13 | public function operate(){ 14 | echo $this->resource."
"; 15 | } 16 | } 17 | 18 | class shareFlyWeight extends Resources{ 19 | private $resources = array(); 20 | 21 | public function get_resource($resource_str){ 22 | if(isset($this->resources[$resource_str])) { 23 | return $this->resources[$resource_str]; 24 | }else { 25 | return $this->resources[$resource_str] = $resource_str; 26 | } 27 | } 28 | 29 | public function operate(){ 30 | foreach ($this->resources as $key => $resources) { 31 | echo $key.":".$resources."
"; 32 | } 33 | } 34 | } 35 | 36 | 37 | // client 38 | $flyweight = new shareFlyWeight(); 39 | $flyweight->get_resource('a'); 40 | $flyweight->operate(); 41 | 42 | $flyweight->get_resource('b'); 43 | $flyweight->operate(); 44 | 45 | $flyweight->get_resource('c'); 46 | $flyweight->operate(); 47 | 48 | // 不共享的对象,单独调用 49 | $uflyweight = new unShareFlyWeight('A'); 50 | $uflyweight->operate(); 51 | 52 | $uflyweight = new unShareFlyWeight('B'); 53 | $uflyweight->operate(); -------------------------------------------------------------------------------- /interpreter/interpreter.php: -------------------------------------------------------------------------------- 1 | interpreter($temp); 41 | echo "
"; 42 | } 43 | } 44 | } 45 | 46 | //client 47 | $obj = new Interpreter(); 48 | $obj->execute("123s45abc"); 49 | ?> -------------------------------------------------------------------------------- /decorator/decorator.php: -------------------------------------------------------------------------------- 1 | _component = $component; 10 | } 11 | public function operation() { 12 | $this->_component->operation(); 13 | } 14 | } 15 | 16 | class ConcreteDecoratorA extends Decorator { // 具体装饰类A 17 | public function __construct(Component $component) { 18 | parent::__construct($component); 19 | } 20 | public function operation() { 21 | parent::operation(); // 调用装饰类的操作 22 | $this->addedOperationA(); // 新增加的操作 23 | } 24 | public function addedOperationA() {echo 'A加点酱油;';} 25 | } 26 | 27 | class ConcreteDecoratorB extends Decorator { // 具体装饰类B 28 | public function __construct(Component $component) { 29 | parent::__construct($component); 30 | } 31 | public function operation() { 32 | parent::operation(); 33 | $this->addedOperationB(); 34 | } 35 | public function addedOperationB() {echo "B加点辣椒;";} 36 | } 37 | 38 | class ConcreteComponent implements Component{ //具体组件类 39 | public function operation() {} 40 | } 41 | 42 | // clients 43 | $component = new ConcreteComponent(); 44 | $decoratorA = new ConcreteDecoratorA($component); 45 | $decoratorB = new ConcreteDecoratorB($decoratorA); 46 | 47 | $decoratorA->operation(); 48 | echo '
--------
'; 49 | $decoratorB->operation(); 50 | ?> -------------------------------------------------------------------------------- /mediator/mediator.php: -------------------------------------------------------------------------------- 1 | _mediator = $mediator; 10 | } 11 | public function send($message) { 12 | $this->_mediator->send($message,$this); 13 | } 14 | abstract public function notify($message); 15 | } 16 | 17 | class ConcreteMediator extends Mediator { // 具体中介者角色 18 | private $_colleague1 = null; 19 | private $_colleague2 = null; 20 | public function send($message,$colleague) { 21 | //echo $colleague->notify($message); 22 | if($colleague == $this->_colleague1) { 23 | $this->_colleague1->notify($message); 24 | } else { 25 | $this->_colleague2->notify($message); 26 | } 27 | } 28 | public function set($colleague1,$colleague2) { 29 | $this->_colleague1 = $colleague1; 30 | $this->_colleague2 = $colleague2; 31 | } 32 | } 33 | 34 | class Colleague1 extends Colleague { // 具体对象角色 35 | public function notify($message) { 36 | echo 'colleague1:'.$message."
"; 37 | } 38 | } 39 | 40 | class Colleague2 extends Colleague { // 具体对象角色 41 | public function notify($message) { 42 | echo 'colleague2:'.$message."
"; 43 | } 44 | } 45 | 46 | // client 47 | $objMediator = new ConcreteMediator(); 48 | $objC1 = new Colleague1($objMediator); 49 | $objC2 = new Colleague2($objMediator); 50 | $objMediator->set($objC1,$objC2); 51 | $objC1->send("to c2 from c1"); 52 | $objC2->send("to c1 from c2"); 53 | ?> -------------------------------------------------------------------------------- /state/state.php: -------------------------------------------------------------------------------- 1 | "; 18 | $context->setState(ConcreteStateB::getInstance()); 19 | } 20 | 21 | } 22 | 23 | class ConcreteStateB implements State { // 具体状态角色B 24 | private static $_instance = null; 25 | private function __construct() {} 26 | public static function getInstance() { 27 | if (is_null(self::$_instance)) { 28 | self::$_instance = new ConcreteStateB(); 29 | } 30 | return self::$_instance; 31 | } 32 | 33 | public function handle(Context $context) { 34 | echo 'concrete_b'."
"; 35 | $context->setState(ConcreteStateA::getInstance()); 36 | } 37 | } 38 | 39 | class Context { // 环境角色 40 | private $_state; 41 | public function __construct() { // 默认为stateA 42 | $this->_state = ConcreteStateA::getInstance(); 43 | } 44 | public function setState(State $state) { 45 | $this->_state = $state; 46 | } 47 | public function request() { 48 | $this->_state->handle($this); 49 | } 50 | } 51 | 52 | // client 53 | $context = new Context(); 54 | $context->request(); 55 | $context->request(); 56 | $context->request(); 57 | $context->request(); 58 | ?> -------------------------------------------------------------------------------- /memento/memento.php: -------------------------------------------------------------------------------- 1 | _state = ''; 7 | } 8 | public function createMemento() { // 创建备忘录 9 | return new Memento($this->_state); 10 | } 11 | public function restoreMemento(Memento $memento) { // 将发起人恢复到备忘录对象记录的状态上 12 | $this->_state = $memento->getState(); 13 | } 14 | public function setState($state) { $this->_state = $state; } 15 | public function getState() { return $this->_state; } 16 | public function showState() { 17 | echo $this->_state;echo "
"; 18 | } 19 | 20 | } 21 | 22 | class Memento { // 备忘录(Memento)角色 23 | private $_state; 24 | public function __construct($state) { 25 | $this->setState($state); 26 | } 27 | public function getState() { return $this->_state; } 28 | public function setState($state) { $this->_state = $state;} 29 | } 30 | 31 | class Caretaker { // 负责人(Caretaker)角色 32 | private $_memento; 33 | public function getMemento() { return $this->_memento; } 34 | public function setMemento(Memento $memento) { $this->_memento = $memento; } 35 | } 36 | 37 | // client 38 | /* 创建目标对象 */ 39 | $org = new Originator(); 40 | $org->setState('open'); 41 | $org->showState(); 42 | 43 | /* 创建备忘 */ 44 | $memento = $org->createMemento(); 45 | 46 | /* 通过Caretaker保存此备忘 */ 47 | $caretaker = new Caretaker(); 48 | $caretaker->setMemento($memento); 49 | 50 | /* 改变目标对象的状态 */ 51 | $org->setState('close'); 52 | $org->showState(); 53 | 54 | $org->restoreMemento($memento); 55 | $org->showState(); 56 | 57 | /* 改变目标对象的状态 */ 58 | $org->setState('close'); 59 | $org->showState(); 60 | 61 | /* 还原操作 */ 62 | $org->restoreMemento($caretaker->getMemento()); 63 | $org->showState(); 64 | ?> -------------------------------------------------------------------------------- /observer/observer.php: -------------------------------------------------------------------------------- 1 | 2 | _observers as $obs ){ 18 | $obs->onSendMsg( $this, $name ); 19 | } 20 | } 21 | 22 | public function addObserver( $observer ){ 23 | $this->_observers[]= $observer; 24 | } 25 | 26 | public function removeObserver($observer_name) { 27 | foreach($this->_observers as $index => $observer) { 28 | if ($observer->getName() === $observer_name) { 29 | array_splice($this->_observers, $index, 1); 30 | return; 31 | } 32 | } 33 | } 34 | } 35 | 36 | class UserListLogger implements IObserver{ 37 | public function onSendMsg( $sender, $args ){ 38 | echo( "'$args' send to UserListLogger\n" ); 39 | } 40 | 41 | public function getName(){ 42 | return 'UserListLogger'; 43 | } 44 | } 45 | 46 | class OtherObserver implements IObserver{ 47 | public function onSendMsg( $sender, $args ){ 48 | echo( "'$args' send to OtherObserver\n" ); 49 | } 50 | 51 | public function getName(){ 52 | return 'OtherObserver'; 53 | } 54 | } 55 | 56 | 57 | $ul = new UserList();//被观察者 58 | $ul->addObserver( new UserListLogger() );//增加观察者 59 | $ul->addObserver( new OtherObserver() );//增加观察者 60 | $ul->sendMsg( "Jack" );//发送消息到观察者 61 | 62 | $ul->removeObserver('UserListLogger');//移除观察者 63 | $ul->sendMsg("hello");//发送消息到观察者 64 | ?> -------------------------------------------------------------------------------- /facade/facade.php: -------------------------------------------------------------------------------- 1 | _camera1 = new Camera(); 35 | $this->_camera2 = new Camera(); 36 | 37 | $this->_light1 = new Light(); 38 | $this->_light2 = new Light(); 39 | $this->_light3 = new Light(); 40 | 41 | $this->_sensor = new Sensor(); 42 | $this->_alarm = new Alarm(); 43 | } 44 | 45 | public function activate() { 46 | $this->_camera1->turnOn(); 47 | $this->_camera2->turnOn(); 48 | 49 | $this->_light1->turnOn(); 50 | $this->_light2->turnOn(); 51 | $this->_light3->turnOn(); 52 | 53 | $this->_sensor->activate(); 54 | $this->_alarm->activate(); 55 | } 56 | 57 | public function deactivate() { 58 | $this->_camera1->turnOff(); 59 | $this->_camera2->turnOff(); 60 | 61 | $this->_light1->turnOff(); 62 | $this->_light2->turnOff(); 63 | $this->_light3->turnOff(); 64 | 65 | $this->_sensor->deactivate(); 66 | $this->_alarm->deactivate(); 67 | } 68 | } 69 | 70 | 71 | //client 72 | $security = new SecurityFacade(); 73 | $security->activate(); 74 | ?> -------------------------------------------------------------------------------- /visitor/visitor.php: -------------------------------------------------------------------------------- 1 | _name = $name; } 24 | public function getName() { return $this->_name; } 25 | public function accept(Visitor $visitor) { // 接受访问者调用它针对该元素的新方法 26 | $visitor->visitConcreteElementA($this); 27 | } 28 | } 29 | 30 | class ConcreteElementB implements Element { // 具体元素B 31 | private $_name; 32 | public function __construct($name) { $this->_name = $name;} 33 | public function getName() { return $this->_name; } 34 | public function accept(Visitor $visitor) { // 接受访问者调用它针对该元素的新方法 35 | $visitor->visitConcreteElementB($this); 36 | } 37 | } 38 | 39 | class ObjectStructure { // 对象结构 即元素的集合 40 | private $_collection; 41 | public function __construct() { $this->_collection = array(); } 42 | public function attach(Element $element) { 43 | return array_push($this->_collection, $element); 44 | } 45 | public function detach(Element $element) { 46 | $index = array_search($element, $this->_collection); 47 | if ($index !== FALSE) { 48 | unset($this->_collection[$index]); 49 | } 50 | return $index; 51 | } 52 | public function accept(Visitor $visitor) { 53 | foreach ($this->_collection as $element) { 54 | $element->accept($visitor); 55 | } 56 | } 57 | } 58 | 59 | // client 60 | $elementA = new ConcreteElementA("ElementA"); 61 | $elementB = new ConcreteElementB("ElementB"); 62 | $elementA2 = new ConcreteElementB("ElementA2"); 63 | $visitor1 = new ConcreteVisitor1(); 64 | $visitor2 = new ConcreteVisitor2(); 65 | 66 | $os = new ObjectStructure(); 67 | $os->attach($elementA); 68 | $os->attach($elementB); 69 | $os->attach($elementA2); 70 | $os->detach($elementA); 71 | $os->accept($visitor1); 72 | $os->accept($visitor2); 73 | ?> -------------------------------------------------------------------------------- /iteration/iteration.php: -------------------------------------------------------------------------------- 1 | _items = $data; 7 | } 8 | public function current() { 9 | return current($this->_items); 10 | } 11 | 12 | public function next() { 13 | next($this->_items); 14 | } 15 | 16 | public function key() { 17 | return key($this->_items); 18 | } 19 | 20 | public function rewind() { 21 | reset($this->_items); 22 | } 23 | 24 | public function valid() { 25 | return ($this->current() !== FALSE); 26 | } 27 | } 28 | 29 | // client 30 | $data = array(1, 2, 3, 4, 5); 31 | $sa = new sample($data); 32 | foreach ($sa AS $key => $row) { 33 | echo $key, ' ', $row, '
'; 34 | } 35 | 36 | 37 | //Yii FrameWork Demo 38 | class CMapIterator implements Iterator { 39 | /** 40 | * @var array the data to be iterated through 41 | */ 42 | private $_d; 43 | /** 44 | * @var array list of keys in the map 45 | */ 46 | private $_keys; 47 | /** 48 | * @var mixed current key 49 | */ 50 | private $_key; 51 | 52 | /** 53 | * Constructor. 54 | * @param array the data to be iterated through 55 | */ 56 | public function __construct(&$data) { 57 | $this->_d=&$data; 58 | $this->_keys=array_keys($data); 59 | } 60 | 61 | /** 62 | * Rewinds internal array pointer. 63 | * This method is required by the interface Iterator. 64 | */ 65 | public function rewind() { 66 | $this->_key=reset($this->_keys); 67 | } 68 | 69 | /** 70 | * Returns the key of the current array element. 71 | * This method is required by the interface Iterator. 72 | * @return mixed the key of the current array element 73 | */ 74 | public function key() { 75 | return $this->_key; 76 | } 77 | 78 | /** 79 | * Returns the current array element. 80 | * This method is required by the interface Iterator. 81 | * @return mixed the current array element 82 | */ 83 | public function current() { 84 | return $this->_d[$this->_key]; 85 | } 86 | 87 | /** 88 | * Moves the internal pointer to the next array element. 89 | * This method is required by the interface Iterator. 90 | */ 91 | public function next() { 92 | $this->_key=next($this->_keys); 93 | } 94 | 95 | /** 96 | * Returns whether there is an element at current position. 97 | * This method is required by the interface Iterator. 98 | * @return boolean 99 | */ 100 | public function valid() { 101 | return $this->_key!==false; 102 | } 103 | } 104 | 105 | $data = array('s1' => 11, 's2' => 22, 's3' => 33); 106 | $it = new CMapIterator($data); 107 | foreach ($it as $row) { 108 | echo $row, '
'; 109 | } 110 | ?> -------------------------------------------------------------------------------- /composite/composite.php: -------------------------------------------------------------------------------- 1 | _composites = array(); } 12 | public function getComposite() { return $this; } 13 | public function operation() { 14 | foreach ($this->_composites as $composite) { 15 | $composite->operation(); 16 | } 17 | } 18 | 19 | public function add(Component $component) { //聚集管理方法 添加一个子对象 20 | $this->_composites[] = $component; 21 | } 22 | 23 | public function remove(Component $component) { // 聚集管理方法 删除一个子对象 24 | foreach ($this->_composites as $key => $row) { 25 | if ($component == $row) { unset($this->_composites[$key]); return TRUE; } 26 | } 27 | return FALSE; 28 | } 29 | 30 | public function getChild() { // 聚集管理方法 返回所有的子对象 31 | return $this->_composites; 32 | } 33 | 34 | } 35 | 36 | class Leaf implements Component { 37 | private $_name; 38 | public function __construct($name) { $this->_name = $name; } 39 | public function operation() {} 40 | public function getComposite() {return null;} 41 | } 42 | 43 | // client 44 | $leaf1 = new Leaf('first'); 45 | $leaf2 = new Leaf('second'); 46 | 47 | $composite = new Composite(); 48 | $composite->add($leaf1); 49 | $composite->add($leaf2); 50 | $composite->operation(); 51 | 52 | $composite->remove($leaf2); 53 | $composite->operation(); 54 | 55 | 56 | 57 | //透明式合成模式 58 | interface Component { // 抽象组件角色 59 | public function getComposite(); // 返回自己的实例 60 | public function operation(); // 示例方法 61 | public function add(Component $component); // 聚集管理方法,添加一个子对象 62 | public function remove(Component $component); // 聚集管理方法 删除一个子对象 63 | public function getChild(); // 聚集管理方法 返回所有的子对象 64 | } 65 | 66 | class Composite implements Component { // 树枝组件角色 67 | private $_composites; 68 | public function __construct() { $this->_composites = array(); } 69 | public function getComposite() { return $this; } 70 | public function operation() { // 示例方法,调用各个子对象的operation方法 71 | foreach ($this->_composites as $composite) { 72 | $composite->operation(); 73 | } 74 | } 75 | public function add(Component $component) { // 聚集管理方法 添加一个子对象 76 | $this->_composites[] = $component; 77 | } 78 | public function remove(Component $component) { // 聚集管理方法 删除一个子对象 79 | foreach ($this->_composites as $key => $row) { 80 | if ($component == $row) { unset($this->_composites[$key]); return TRUE; } 81 | } 82 | return FALSE; 83 | } 84 | public function getChild() { // 聚集管理方法 返回所有的子对象 85 | return $this->_composites; 86 | } 87 | 88 | } 89 | 90 | class Leaf implements Component { 91 | private $_name; 92 | public function __construct($name) {$this->_name = $name;} 93 | public function operation() {echo $this->_name."
";} 94 | public function getComposite() { return null; } 95 | public function add(Component $component) { return FALSE; } 96 | public function remove(Component $component) { return FALSE; } 97 | public function getChild() { return null; } 98 | } 99 | 100 | // client 101 | $leaf1 = new Leaf('first'); 102 | $leaf2 = new Leaf('second'); 103 | 104 | $composite = new Composite(); 105 | $composite->add($leaf1); 106 | $composite->add($leaf2); 107 | $composite->operation(); 108 | 109 | $composite->remove($leaf2); 110 | $composite->operation(); 111 | 112 | ?> --------------------------------------------------------------------------------