class Component
{
protected $name;
public function __construct($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function add(Component $component)
{
throw new RuntimeException('Could not add child.');
}
public function remove(Component $component)
{
throw new RuntimeException('Could not remove child.');
}
public function display()
{
echo $this->name;
}
}
class Composite extends Component
{
private $children = array();
public function add(Component $component)
{
$this->children[] = $component;
}
public function remove(Component $component)
{
foreach ($this->children as $key => $child) {
if ($child == $component) {
unset($this->children[$key]);
}
}
}
public function display()
{
echo $this->name . PHP_EOL;
foreach ($this->children as $child) {
$child->display();
}
}
}
$composite = new Composite("Root");
$composite->add(new Component("Foo"));
$composite->add(new Component("Bar"));
$composite->add(new Component("Baz"));
$composite->display();
PHP代码实现合成模式
最新推荐文章于 2024-07-26 17:57:56 发布