深入理解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 ******************************************************/
相关文章推荐
- 深入理解PHP:高级技巧、面向对象与核心技术(原书第3版) -- 设计模式之单一模式
- 深入理解PHP:高级技巧、面向对象与核心技术(原书第3版) -- 设计模式之工厂模式
- 深入理解PHP:高级技巧、面向对象与核心技术(原书第3版) -- 高级 PHP 技巧
- 深入理解PHP高级技巧、面向对象与核心技术之调整浏览器缓存
- 深入理解PHP:高级技巧、面向对象与核心技术
- 【学习笔记】《深入PHP - 面向对象、模式与实践》(第3版)——第5章 对象工具
- 深入理解JavaScript系列(40):设计模式之组合模式
- 深入理解JavaScript系列(40):设计模式之组合模式详解
- PHP核心技术笔记(2):面向对象的设计原则
- PHP核心技术与最佳实践 读书笔记 第二章 面向对象的设计原则
- 深入理解JavaScript系列(40):设计模式之组合模式
- 深入理解JavaScript系列(40):设计模式之组合模式详解
- PHP面向对象深入理解之四(设计模式-工厂模式)
- 深入理解JavaScript系列(40):设计模式之组合模式
- 深入理解JavaScript系列(40):设计模式之组合模式
- 深入理解JavaScript系列(40):设计模式之组合模式
- 深入理解JavaScript系列(40):设计模式之组合模式
- 深入理解JavaScript系列(40):设计模式之组合模式
- 深入理解JavaScript系列(40):设计模式之组合模式
- PHP面向对象深入理解之四(设计模式-观察者模式)