php实现组合模式
组合模式简介
组合模式(Composite Pattern)是一种结构型设计模式,允许将对象组合成树形结构以表示“部分-整体”的层次关系。客户端可以统一处理单个对象和组合对象,无需关心具体类型。
适用场景
- 需要表示对象的层次结构(如文件系统、菜单树)。
- 希望客户端以统一方式处理单个对象和组合对象。
PHP实现步骤
定义抽象组件
抽象组件声明组合中所有对象的通用接口,可以是抽象类或接口。

<?php
abstract class Component {
protected $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function add(Component $component);
abstract public function remove(Component $component);
abstract public function display($depth);
}
实现叶子组件
叶子组件是组合中的基本元素,没有子组件。
class Leaf extends Component {
public function add(Component $component) {
throw new Exception("Cannot add to a leaf");
}
public function remove(Component $component) {
throw new Exception("Cannot remove from a leaf");
}
public function display($depth) {
echo str_repeat("-", $depth) . $this->name . "\n";
}
}
实现复合组件
复合组件包含子组件,通常存储子组件集合并实现操作逻辑。

class Composite extends Component {
private $children = [];
public function add(Component $component) {
$this->children[] = $component;
}
public function remove(Component $component) {
$index = array_search($component, $this->children);
if ($index !== false) {
unset($this->children[$index]);
}
}
public function display($depth) {
echo str_repeat("-", $depth) . $this->name . "\n";
foreach ($this->children as $child) {
$child->display($depth + 2);
}
}
}
客户端使用示例
客户端通过抽象接口操作组合结构,无需区分叶子或复合组件。
$root = new Composite("Root");
$root->add(new Leaf("Leaf A"));
$root->add(new Leaf("Leaf B"));
$branch = new Composite("Branch X");
$branch->add(new Leaf("Leaf XA"));
$branch->add(new Leaf("Leaf XB"));
$root->add($branch);
$root->display(1);
输出结果
执行后输出树形结构:
-Root
---Leaf A
---Leaf B
---Branch X
-----Leaf XA
-----Leaf XB
关键点
- 透明性:所有组件(叶子/复合)实现相同接口,客户端无需类型判断。
- 递归组合:复合组件的操作(如
display())递归调用子组件。 - 异常处理:叶子组件直接禁止不支持的操作(如
add())。
通过组合模式,可以灵活扩展层次结构,同时保持代码简洁性。






