设计模式 - 结构型【组合模式】

使用场景:

组合模式适用于当我们的一个对象可能代表一个实体,或者一个组合的实体;
比如:雇员->部门、表单元素->HTML表单

表单元素->HTML表单:

abstract class FormComponent(){
	abstract function add(FormComponent $obj);
	abstract function remove(FormComponent $obj);
	abstract function display();
	abstract function validate();
	abstract function showError();
}

class Form extends FormComponent{
	private $_elements = array();
	public function add(FormComponent $obj){
		$this->_elements[] = $obj;
	}
	public function display(){
		//Display the entire form
	}
}

class FormElement extends FormComponent{
	public function add(FormComponent $obj){
		return $obj; //不需要做任何事情,因为我们不需要为这个类型添加子元素,取而代之,这个add方法返回增加的对象,或者FALSE,或者抛出一个异常
	}
	public function display(){
		//display the element
	}
}

$form = new Form();
$email = new FormElement();
$form->add($email);

雇员->部门:

// 两种工作单元的类型:雇员和团队,团队也是由雇员组成的。
// 工作可以分配给两者中的任何一个,也能由其中之一完成
abstract class WorkUnit{
	protected $tasks = array();
	protected $name = NULL;
	public function __construct($name){
		$this->name = $name;
	}
	public function getName(){
		return $this->name;
	}
	abstract public function add(Empoyee $e);
	abstract public function remove(Empoyee $e);
	abstract public function assignTask($task);
	abstract public function completeTask($task);
}
class Team extends WorkUnit{
	private $_employees = array();
	public function add($Employees $e){
		$this->_employees[] = $e;
		echo "<p> {$e->getName()} has been added to team ($this->_getName()).</p>";
	}
	public function remove(Employees $e){
		$index = array_search($e,$this->_employees);
		unset($this->_employees[$index]);
		echo "<p> {$e->getName()} has been removed from team {$this->getName()}.</p>";
	}
	public function assignTask($task){
		$this->tasks[] = $task;
		echo "<p> A new task has been assigned to team {$this->getName()} .It should be easy to do with ($this->getCount()) team member(s).</p>";
	}
	public function completeTask($task){
		$index = array_search($task,$this->tasks);
		unset($this->tasks[$index]);
		echo "<p> The '{$task}' task has been completed by team {$this->getName()}.</p>";
	}
	
	public function getCount(){
		return count($this->_employees);
	}
}
class Employee extends WorkUnit{
	public function add(employee $e){
		return false;
	}
	public function remove(employee $e){
		return false;
	}
	public function assignTask($task){
		$this->tasks[] = $task;
		echo "<p> A new task has been assigned to {$this->getName()}. It will be done by {$this->getName()} alone.</p>";
	}
	public function completeTask($task){
		$index = array_search($task,$this->tasks);
		unset($this->tasks[$index]);
		echo "<p> The '{$task}' task has been completed by employee {$this->getName()}.</p>";
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值