php 设计模式 --组合器模式

PHP 开启错误显示并设置错误报告级别

ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'on');
 
目的:分级处理;整体与结构 树结构;
<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'on');
abstract class Company{
    protected $name;
    function __construct($name){
        $this->name=$name;
    }
    abstract function Add(Company $company);
    abstract function Remove(Company $company);
    abstract function Display($depth);
}


class SubCompany extends Company
{
    private $sub_companys = array();
    function __construct($name){
        parent::__construct($name);
    
    }
    public function Add(Company $company){
        //echo 31;die;
        $this->sub_companys[] = $company;
    }
    function Remove(Company $company) {
        $key = array_search($company , $this->sub_companys);
        if ( $key != false) {
            unset($this->sub_companys[$key]);
        }

    }
    function Display($depth) {
    
        $pre = "";
        for($i=0 ; $i<$depth; $i++){
            $pre.="-";
        }
        $pre.=$this->name."<br/>";
        echo $pre;

        foreach ($this->sub_companys as $v ) {
            $v->Display($depth+2);
        }
    }
} 

class MoneyDept extends Company
{

    function __construct($name){
        parent::__construct($name);
    }

    function Add(Company $company){
        echo "叶子节点,不能再添加。。。<br/>" ;
    }
    function Remove(Company $company) {
        echo "叶子节点,不能再删除。。。<br/>";
    }
    function Display($depth) {
        $pre = "";
        for($i=0 ; $i<$depth; $i++){
            $pre.="-";
        }
        $pre.=$this->name."<br/>";
        echo $pre;
    }
    
}


class ItDept extends Company
{

    function __construct($name){
        parent::__construct($name);
    }

    function Add(Company $company){
        echo "叶子节点,不能再添加。。。<br/>";
    }
    function Remove(Company $company) {
        echo "叶子节点,不能再删除。。。<br/>";
    }
    function Display($depth) {
        $pre = "";
        for($i=0 ; $i<$depth; $i++){
            $pre.="-";
        }
        $pre.=$this->name."<br/>";
        echo $pre;
    }
    
}


$root = new SubCompany("北京总公司");
//$a = new MoneyDept("总公司财务部");
$root->Add(new MoneyDept("总公司财务部"));
$root->Add(new ItDept("总公司技术部门"));



$sh = new SubCompany("上海分公司");
$sh->Add(new MoneyDept("上海分公司财务部"));
$sh->Add(new ItDept("上海分公司技术部门"));
$root->Add($sh);

$root->Display(1);

echo "<br>";
$root->Remove($sh);
$root->Display(3);

 

posted @ 2019-12-18 20:11  千载白云  阅读(205)  评论(0编辑  收藏  举报