<?php
abstract class Component
{
protected $name;
public function __construct($name)
{
$this->name=$name;
}
abstract public function display();
}
class Dir extends Component{
protected $children=[];
public function add(Component $component){
$this->children[]=$component;
}
public function display()
{
// TODO: Implement display() method.
$namestr=$this->name.'<br>';
foreach ($this->children as $child) {
$namestr.='--'.$child->display();
}
return $namestr;
}
}
class File extends Component{
public function add(Component $component)
{
throw new \Exception('文件不能添加子节点');
}
public function display(){
return '--'.$this->name .'<br>';
}
}
class Index{
public function run(){
$design=new Dir("Design");
$dir1=new Dir("dir1");
$dir2=new Dir("dir2");
$design->add($dir1);
$design->add($dir2);
$file1=new File("file1");
$file2=new File("file2");
$dir1->add($file1);
$dir1->add($file2);
echo $design->display();
}
}
$client=new Index();
$client->run();
安全组合模式
最新推荐文章于 2021-07-01 23:27:08 发布