组合模式
将对象组合成树形结构以表示“部分-整体”的层次结构。这种模式的关键在于类中创建了一个包含自己对象的属性集合。
应用
菜单设计,文件夹结构等。
实例
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?php class Menu { /** * @var string */ private $_name; /** * @var Menu[] */ private $_subMenus; function __construct($name) { $this->_name = $name; $this->_subMenus = []; } function addSubMenu($menu) { $this->_subMenus[] = $menu; } function removeSubMenu($menu) { foreach ($this->_subMenus as $index => $subMenu) { if ($subMenu == $menu) unset($this->_subMenus[$index]); } } function getSubMenus() { return $this->_subMenus; } function toString() { echo $this->_name . " "; } } $root = new Menu('功能菜单'); $headMenu1 = new Menu('设置'); $headMenu2 = new Menu('管理'); $subMenu1 = new Menu('更新系统'); $subMenu2 = new Menu('关闭系统'); $subMenu3 = new Menu('用户系统'); $subMenu4 = new Menu('用户组系统'); $root->addSubMenu($headMenu1); $root->addSubMenu($headMenu2); $headMenu1->addSubMenu($subMenu1); $headMenu1->addSubMenu($subMenu2); $headMenu2->addSubMenu($subMenu3); $headMenu2->addSubMenu($subMenu4); $root->toString(); foreach ($root->getSubMenus() as $headMenu) { $headMenu->toString(); foreach ($headMenu->getSubMenus() as $subMenu) { $subMenu->toString(); } }