大家都知道,一个企业是有多个部们共同组成,相互协作以实现效率最大化。一个企业的组成是由多个元素组成的,其中最基本的是“人”这个元素,多个人组成一个team,多个team组成一个部门,多个部分组成一个公司。
对于一个公司的组织结构,我们如何用代码表示,同时要满足,对于元素(人/对我/部门/公司)的使用,能使用相同的接口。即整体的调用方式和单个的元素的调用方式一致。
组织结构:
公司
部门1
team1
person1
person2
....
team2
部门2
team1
team2
代码实现:
//首先是人元素,这是最基本的元素
class person {
private $_name = null;
private $_department = null;
private $_team = null;
private $_position = null;
public function setName($name) {
$this->_name = $name;
}
public function getName() {
return $this->_name;
}
public function setDepartment($department) {
$this->_department = $department;
}
public function getDepartment() {
return $this->_department;
}
public function setPosition($position) {
$this->_position = $position;
}
public function getPosition() {
return $this->_position;
}
public function getInfo() {
echo " 姓名:{$this->_name}, 部门:{$this->_department}, 职位:{$this->_position}<br>";
}
}
//部门/队伍 元素
class Department {
private $_departmentElement = [];
private $_department = null;
public function __construct($name) {
$this->_department = $name;
}
public function setDepartment($name) {
$this->_department = $name;
}
public function getDepartment() {
return $this->_department;
}
public function addElement($element) {
$this->_departmentElement[] = $element;
}
public function getElements() {
return $this->_departmentElement;
}
public function showDepartmentInfos($department = null) {
$department = is_null($department)?$this:$department;
echo '<br>'.$department->getDepartment().'<br>';
echo "<br>-------------------------<br>";
$departmentElement = $department->getElements();
foreach($departmentElement as $vals) {
if($vals instanceof Department) {
$this->showDepartmentInfos($vals);
}
else {
$vals->getInfo();
}
}
}
}
//使用方式
$Company = new Department('XXX科技'); //公司名称
$TeamA1 = new Department('A部门-1队');
for($i=-0; $i<6; $i++) {
$person = new person();
$person->setName("A1姓名".rand(1,100));
$person->setPosition('员工');
$TeamA1->addElement($person);
}
$TeamA2 = new Department('A部门-2队');
for($i=-0; $i<6; $i++) {
$person = new person();
$person->setName("A2姓名".rand(1,100));
$person->setPosition('员工');
$TeamA2->addElement($person);
}
$DepartmentA = new Department('A部门');
$DepartmentB = new Department('B部门');
$DepartmentA->addElement($TeamA1); //$TeamA1->showDepartmentInfos(); //都和company调用相似,客户用一致的方式来处理对象集合和单个对象
$DepartmentA->addElement($TeamA2); //$TeamA2->showDepartmentInfos();
$DepartmentB->addElement($TeamA1); //$DepartmentA->showDepartmentInfos();
$DepartmentB->addElement($TeamA2); //$DepartmentB->showDepartmentInfos();
$Company->addElement($DepartmentA);
$Company->addElement($DepartmentB);
$Company->showDepartmentInfos(); //调用公司信息
而上面的实现方式就是今天的主角--组合模式
组合模式的优点:
1.它描述了如何构造一个类层次式结构,这一结构由两种类型的对象(基元对象和组合对象)所对应的类构成 . 其中的组合对象使得你可以组合基元对象以及其他的组合对象,从而形成任意复杂的结构。
2.客户用一致的方式来处理对象集合和单个对象
3.简化客户代码 客户可以一致地使用组合结构和单个对象。通常用户不知道 (也不关心)
处理的是一个叶节点还是一个组合组件。