设计模式之组合模式(PHP实现)
2024-10-21 15:32:44
github地址:https://github.com/ZQCard/design_pattern
/**
组合模式(Composite Pattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。
这种模式创建了一个包含自己对象组的类。该类提供了修改相同对象组的方式。
* 组合模式(Composite Pattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。
* 组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。
* 这种模式创建了一个包含自己对象组的类。该类提供了修改相同对象组的方式。
* 我们通过下面的实例来演示组合模式的用法。实例演示了一个组织中员工的层次结构。
*/
(1)Employee.class.php
<?php namespace Composite; class Employee
{
private $name;
private $dept;
private $salary;
private $subordinates = []; public function __construct($name, $dept, $salary)
{
$this->name = $name;
$this->dept = $dept;
$this->salary = $salary;
} public function add(Employee $employee)
{
$this->subordinates[] = $employee;
} public function remove(Employee $employee)
{ } public function getSubordinates()
{
return $this->subordinates;
}
}
(2)composite.php
<?php
spl_autoload_register(function ($className){
$className = str_replace('\\','/',$className);
include $className.".class.php";
}); use Composite\Employee; $CEO = new Employee("John","CEO", 30000); $headSales = new Employee("Robert","Head Sales", 20000); $headMarketing = new Employee("Michel","Head Marketing", 20000); $clerk1 = new Employee("Laura","Marketing", 10000);
$clerk2 = new Employee("Bob","Marketing", 10000); $salesExecutive1 = new Employee("Richard","Sales", 10000);
$salesExecutive2 = new Employee("Rob","Sales", 10000); $CEO->add($headSales);
$CEO->add($headMarketing); $headSales->add($salesExecutive1);
$headSales->add($salesExecutive2); $headMarketing->add($clerk1);
$headMarketing->add($clerk2); $subordinates = $CEO->getSubordinates();
echo '<pre/>';
var_dump($subordinates);die;
最新文章
- RavenDB官网文档翻译系列第二
- javax.validation.ConstraintViolationException---Hibernate后台实体校验
- [译]ASP.NET 5: New configuration files and containers
- Git环境的搭建及使用
- php 计算本月第一天 本月最后一天 下个月第一天
- SpringMVC上传(通过物理路径)
- Wordpress 音频播放器 Wordpress audio player with jQuery audioplayer.swf
- Extjs4新特性
- PAT乙级 1065. 单身狗(25) by Python
- mybatis中的mapper接口文件以及example类的实例函数以及详解
- 求m区间内的最小值
- Credit Summaries &; Importing External Credit Exposure
- P1417 烹调方案 (0/1背包+贪心)
- MINIST深度学习识别:python全连接神经网络和pytorch LeNet CNN网络训练实现及比较(三)
- t-SNE完整笔记
- Docker网络的基本功能操作示例
- 10.Django用户认证组件
- Angular 4 辅助路由
- arcgis10.3下载,arcgis pro的下载地址
- 【spoj SUBST1】 New Distinct Substrings