组合模式
以单个对象的方式来对待一组对象。 有点类似递归处理 组合模式(Composite Pattern)有时候又叫做部分-整体模式,用于将对象组合成树形结构以表示“部分-整体”的层次关系。组合模式使得用户对单个对象和组合对象的使用具有一致性。 常见使用场景:如树形菜单、文件夹菜单、部门组织架构图等。
1 <?php 2 3 interface Renderable 4 { 5 public function render(); 6 } 7 8 9 class Form implements Renderable 10 { 11 private $elements; 12 13 /** 14 * runs through all elements and calls render() on them, then returns the complete representation 15 * of the form. 16 * 17 * from the outside, one will not see this and the form will act like a single object instance 18 * 19 * @return string 20 */ 21 public function render() 22 { 23 $formCode = ''; 24 25 foreach ($this->elements as $e) { 26 $formCode .= $e->render(); 27 } 28 29 return $formCode; 30 } 31 32 public function addElement(\Renderable $element) 33 { 34 $this->elements[spl_object_hash($element)] = $element; 35 } 36 37 public function removeElement(\Renderable $element) 38 { 39 unset($this->elements[spl_object_hash($element)]); 40 } 41 } 42 43 class InputElement implements Renderable 44 { 45 private $_name; 46 47 public function __construct($name) 48 { 49 $this->_name = $name; 50 } 51 52 public function render() 53 { 54 return "<input name='".$this->_name."' placeholder='Please input your name' />"; 55 } 56 } 57 58 class TextElement implements Renderable 59 { 60 private $_name; 61 62 public function __construct($name) 63 { 64 $this->_name = $name; 65 } 66 67 public function render() 68 { 69 return "<textarea cols='5' rows='3' name='".$this->_name."'></textarea>"; 70 } 71 } 72 73 74 75 $form = new Form(); 76 $input = new InputElement('name'); 77 $text = new TextElement('text'); 78 79 $form->addElement($input); 80 $form->addElement($text); 81 82 $embed = new Form(); 83 $embed->addElement($input); 84 $embed->addElement($text); 85 86 $form->addElement($embed); 87 88 89 print htmlspecialchars($form->render());