您的位置:首页 > 编程语言 > PHP开发

深入理解PHP:高级技巧、面向对象与核心技术(原书第3版) -- 设计模式之组合模式

2017-09-18 22:07 966 查看
<?php

// 使用类型:
// 1. 你想表示对象的部分-整体层次结构。
// 2. 你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。
// 通俗的讲:一个单一的实体和一个组合的实体,需要使用同样的方式去实现,这时候就需要想到用组合模式。
abstract class WorkUnit
{
protected $tasks = [];
protected $name = null;

function __construct($name)
{
$this->name = $name;
}

function getName()
{
return $this->name;
}

abstract function add(Employee $e);

abstract function remove(Employee $e);

abstract function assignTask($task);

abstract function completeTask($task);
}

class Team extends WorkUnit
{
private $_employees = [];

function add(Employee $e)
{
$this->_employees[] = $e;
echo "add an e to team <br />";
}

function remove(Employee $e)
{
$index = array_search($e, $this->_employees);
unset($this->_employees[$index]);
echo "remove an e from team <br />";
}
function assignTask($task)
{
$this->tasks[] = $task;
echo "assign a task to {$this->getName()}, will be made by {$this->getCount()} members <br />";
}

function completeTask($task)
{
$index = array_search($task, $this->tasks);
unset($this->tasks[$index]);
echo "the team {$this->getName()} has done this task <br />";
}

function getCount()
{
return count($this->_employees);
}
}

class Employee extends WorkUnit
{
function add(Employee $e)
{
return false;
}

function remove(Employee $e)
{
return false;
}

function assignTask($task)
{
$this->tasks[] = $task;
echo "assign a task to person {$this->getName()}! <br />";
}

function completeTask($task)
{
$index = array_search($task, $this->tasks);
unset($this->tasks[$index]);
echo "the person {$this->getName()} has done this task <br />";
}
}
$superTeam=new Team("superTeam");
$leon=new Employee("leon");
$helen=new Employee("helen");
$superTeam->add($leon);
$superTeam->add($helen);
$leon->assignTask("clean the door");
$superTeam->assignTask("save the world");
$superTeam->completeTask("we change the world");

/************************* 输出 *************************
add an e to team
add an e to team
assign a task to person leon!
assign a task to superTeam, will be made by 2 members
the team superTeam has done this task
******************************************************/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐