温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

php组合模式

发布时间:2020-08-19 16:15:27 来源:网络 阅读:307 作者:penyanlu 栏目:web开发

组合模式应用于递归结构的优化或分层数据结构的管理:

<?php

abstract class Compary

{

protected $name;

/* public function __construct($name)

{

$this->name=$name;

}  */

abstract public  function Add(Compary $compary);

abstract public  function Move(Compary $compary);

abstract public  function Display($level=0);

}


class SubCompary extends Compary

{

private $subcompary=array();

//protected $name;

public function __construct($name)

{

//parent::$name=$name;

$this->name=$name;

}

public function Add(Compary $compary)

{

if(!$compary)

{

return false;

}

$key=array_search($compary,$this->subcompary);

if($key===false)

{

$this->subcompary[]=$compary;

}

return true;

}

public function Move(Compary $compary)

{

if(!$compary)

{

return false;

}

$key=array_search($compary,$this->subcompary);

if($key!==false)

{

unset($this->subcompary[$key]);

}

return true;

}

public function Display($level=0)

{

//输出本节点的名称

if($this->name)

{

$pre='';

for($i=0;$i<$level;$i++)

{

$pre.='-';

}

echo $pre.$this->name.'<br/>';

}

//按层次输出每个分层的节点的名称

if(is_array($this->subcompary))

{

foreach($this->subcompary as $key => $value )

{

//递归输出每层的节点名称

//递归输出每层的节点名称

$value->Display($level+2);

}

}

else

{

}

}

}

class Department extends Compary

{

private $department=array();

//protected $name;

public function __construct($name)

{

//parent::$name=$name;

$this->name=$name;

}

public function Add(Compary $compary)

{

/* if(!$compary)

{

return false;

}

$key=array_search($compary,$this->dapartment);

if($key===false)

{

$this->dapartment[]=$compaty;

return true;

}

else

{

return false;

} */

echo '叶子节点不能增加节点!';

}

public function Move(Compary $compary)

{

/* if(!$compary)

{

return false;

}

$key=array_search($compary,$this->department);

if($key!==false)

{

unset($this->department[$key]);

return true;

}

else

{

return false;

} */

echo '叶子节点不能删除节点!';

}

public function Display($level=0)

{

if(!$this->name)

{

return false;

}

$pre='';

for($i=0;$i<$level;$i++)

{

$pre.='-';

}

echo $pre.$this->name.'<br/>';

/* if(is_array($this->department))

{

foreach($this->department as $key => $value )

{

$value->Display($level+2);

}

}

else

{

return false;

} */

}

}

header('content-type:text/html;charset=utf-8');

$subcompary=new SubCompary('北京公司');



$subcompary->Add(new Department('总公司财务部'));

$subcompary->Add(new Department('总公司技术部'));


$shanghai=new SubCompary('上海分公司');

$shanghai->Add(new Department('上海分公司技术部'));

$shanghai->Add(new Department('上海分公司财务部'));


$subcompary->Add($shanghai);


$subcompary->Display(2);


?>


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI