说明
又叫部分-整体模式,在处理类似树形结构的问题时比较方便。
示例
下面看下组合模式的代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| class TreeNode{ private string $name; private TreeNode $parent; private ?TreeNode $children=null;
public function __construct(string $name){ $this->name = $name; } public function getName(): string{ return $this->name; } public function setName(string $name){ $this->name = $name; }
public function getParent(): TreeNode{ return $this->parent; }
public function setParent(TreeNode $parent){ $this->parent = $parent; }
public function add(TreeNode $node){ $this->children = $node; } public function remove(TreeNode $node){ $this->children->remove($node); } public function getChildren(): ?TreeNode{ return $this->children; } }
$root = new TreeNode('A'); $nodeB = new TreeNode('B'); $nodeC = new TreeNode('C');
$nodeB->add($nodeC); $root->add($nodeB); print_r($root); echo "build the tree finished!";
|
总结
使用场景:将多个对象组合在一起进行操作,常用于表示树形结构中,例如二叉树,数等。