以下是一个简单的 PHP 组合模式的示例:
// 抽象构件
interface Component {
public function operation();
}
// 叶子构件
class Leaf implements Component {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function operation() {
return "Leaf: " . $this->name;
}
}
// 容器构件
class Composite implements Component {
private $name;
private $children = [];
public function __construct($name) {
$this->name = $name;
}
public function add(Component $component) {
$this->children[] = $component;
}
public function operation() {
$result = "Composite: " . $this->name . " with ";
foreach ($this->children as $child) {
$result .= $child->operation() . " ";
}
return $result;
}
}
// 客户端代码
$leaf1 = new Leaf("Leaf1");
$leaf2 = new Leaf("Leaf2");
$composite = new Composite("Composite1");
$composite->add($leaf1);
$composite->add($leaf2);
echo $composite->operation();
// 输出 "Composite: Composite1 with Leaf: Leaf1 Leaf: Leaf2"
在这个例子中,Component 是抽象构件接口,定义了叶子构件和容器构件的公共操作。Leaf 是叶子构件,它表示树中的叶子节点。Composite 是容器构件,它可以包含其他叶子或容器构件,形成树形结构。
通过组合模式,客户端可以对待叶子构件和容器构件的方式进行统一的处理,而无需关心具体是哪一种类型的构件。这样的设计模式在处理树形结构数据或对象时非常有用,使得整体与部分之间的操作更加一致。
转载请注明出处:http://www.pingtaimeng.com/article/detail/11942/PHP