PHP组合模式Composite Pattern优点与实现过程(php图片上传代码详解)这都可以

随心笔谈12个月前发布 admin
85 0

<?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)
{
echo “Cannot add to a leaf.”;
}
public function remove(Component $component)
{
echo “Cannot remove from a leaf.”;
}
public function display($depth)
{
echo str_repeat(“-“, $depth) . $this->name . “\n”;
}
}
// 容器组件
class Composite extends Component
{
private $children=array();
public function add(Component $component)
{
array_push($this->children, $component);
}
public function remove(Component $component)
{
$key=array_search($component, $this->children, true);
if ($key !==false) {
unset($this->children[$key]);
}
}
public function display($depth)
{
echo str_repeat(“-“, $depth) . $this->name . “\n”;
foreach ($this->children as $component) {
$component->display($depth + 2);
}
}
}
// 客户端代码
$root=new Composite(“root”);
$root->add(new Leaf(“Leaf A”));
$root->add(new Leaf(“Leaf B”));
$comp=new Composite(“Composite X”);
$comp->add(new Leaf(“Leaf XA”));
$comp->add(new Leaf(“Leaf XB”));
$root->add($comp);
$root->add(new Leaf(“Leaf C”));
$leaf=new Leaf(“Leaf D”);
$root->add($leaf);
$root->remove($leaf);
$root->display(1);

© 版权声明

相关文章