Home>Article>Backend Development> PHP design pattern combination pattern
This article introduces the combination mode of PHP design pattern, which has a certain reference value. Now I share it with you. Friends in need can refer to it
Combinator (Composite) Patternis one of the structural patterns in design patterns. Its main purpose is to combine multiple objects into a tree-like structure to represent the "whole-part" relationship.
Example: We use a tree diagram to represent Jiangsu Province->Nanjing City->Qinhuai District and Jianye District.
Among them, Jiangsu Province is the first level, Nanjing City belongs to Jiangsu Province and is the second level, while Jianye District and Qinhuai District belong to Nanjing City and are the third level.
You will get the structure as shown:
-->江苏省 1级 -->-->南京市 2级 -->-->-->秦淮区 3级 -->-->-->建邺区 3级
The role of the combiner mode is that the client combines objects through the same method and distinguishes the master-slave level, improving flexibility and scalability.
name = $name; } abstract function Add(IComposite $place); abstract function Display($level); } /** 组合器类 供客户端调用 * Composite */ Class Composite extends IComposite { private $places = array(); function __construct($name) { parent::__construct($name); } function Add(IComposite $place) { $this->places[] = $place; } /** 显示方法 * Display * $level 级别 默认江苏省为 1级 */ function Display($level = "1") { $pre = ""; for ($i=0; $i < $level; $i++) { $pre.= "-->"; } $pre.=$this->name."
"; echo $pre; foreach ($this->places as $v) { // 往后南京市 级别加1 秦淮区在南京市基础上再加1 $v->display($level+1); } } }
Add($nanjing); // 把秦淮区和建邺区添加到南京市下 $nanjing->Add($qinhuai); $nanjing->Add($jianye); $jiangsu->Display(); // 显示
Related recommendations:
PHP Design Pattern Bridge Mode
PHP Design Pattern Adapter Mode
PHP Design Pattern Builder Pattern
The above is the detailed content of PHP design pattern combination pattern. For more information, please follow other related articles on the PHP Chinese website!