组合模式

类图

2024072113364936.png

比较简单,直接上代码

代码

<?php
 
// Component接口,定义了叶子和组合对象的共同操作
interface Component
{
public function operation(): string;
}
 
// 叶子节点,表示组合的最基本单元
class Leaf implements Component
{
private $name;
 
public function __construct($name)
{
$this->name = $name;
}
 
public function operation(): string
{
return "Leaf " . $this->name;
}
}
 
// 组合节点,表示可以包含其他叶子或组合的对象
class Composite implements Component
{
private $children = [];
 
public function add(Component $component)
{
$this->children[] = $component;
}
 
public function remove(Component $component)
{
$this->children = array_filter($this->children, function ($child) use ($component) {
return $child !== $component;
});
}
 
public function operation(): string
{
$result = "Composite (";
foreach ($this->children as $child) {
$result .= $child->operation() . " ";
}
$result = rtrim($result) . ")";
return $result;
}
}
 
// 客户端代码可以统一处理组合和叶子对象
function clientCode(Component $component)
{
echo "RESULT: " . $component->operation() . "\n";
}
 
// 创建叶子对象
$leaf1 = new Leaf("A");
$leaf2 = new Leaf("B");
 
// 创建组合对象
$composite = new Composite();
$composite->add($leaf1);
$composite->add($leaf2);
 
// 创建更大的组合对象
$composite2 = new Composite();
$composite2->add($composite);
$composite2->add(new Leaf("C"));
 
echo "Client: I've got a simple component:\n";
clientCode($leaf1);
 
echo "\nClient: Now I've got a composite tree:\n";
clientCode($composite2);