使用场景:
组合模式适用于当我们的一个对象可能代表一个实体,或者一个组合的实体;
比如:雇员->部门、表单元素->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>";
}
}