介绍
组合模式(Composite Pattern)是将一组相似的对象依照树形结构来组合成一个单一对象,用来表示整体和部分层次,属于结构型模式。
代码实例
公司有很多员工,根据部门、职级进行划分,员工之间的关系很适合用一种树形结构来表示。
<?php
class Company
{
public $department;
public $level;
public $name;
public $employeeList;
public function __construct($department, $name, $level)
{
$this->department = $department;
$this->name = $name;
$this->level = $level;
}
public function addEmployee($employee)
{
$this->employeeList[] = $employee;
}
}
class CompanyDemo
{
public function getAllEmployee()
{
$sales_department = new Company('sales','Lida', 1);
$sales_department->addEmployee(new Company('sales','Penny', 2));
$sales_department->addEmployee(new Company('sales','Amy', 2));
var_dump($sales_department);
}
}
$companyDemo = new CompanyDemo();
$companyDemo->getAllEmployee();
总结
组合模式生成结构对象为树状的对象,可以由客户端对整体和单一对象同时调用,但是该模式违反了 依赖倒置 原则。
网友评论