美文网首页PHP开发PHP经验分享
编程中的设计模式之组合模式

编程中的设计模式之组合模式

作者: phpworkerman | 来源:发表于2020-08-16 21:57 被阅读0次
介绍

组合模式(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();
总结

组合模式生成结构对象为树状的对象,可以由客户端对整体和单一对象同时调用,但是该模式违反了 依赖倒置 原则。

相关文章

网友评论

    本文标题:编程中的设计模式之组合模式

    本文链接:https://www.haomeiwen.com/subject/pvkndktx.html