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

随心笔谈1年前发布 编辑
150 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);

© 版权声明

相关文章