Home Backend Development PHP Tutorial Tree-like composite pattern

Tree-like composite pattern

Nov 12, 2016 pm 02:08 PM
php

A company is composed of members who work. Each member has different attributes (name, position, salary), forming a tree structure according to different levels. The general manager is the root node of this tree because he has no superiors. The department manager is the branch node because he has both superiors and subordinates. The minions are the leaf nodes because he is the lowest-level hard worker and has no subordinates. Now use the combination mode to display this tree. Class diagram:

Tree-like composite pattern

The code is as follows:

<?php
abstract class Corp {
private $name = &#39;&#39;;
private $position = &#39;&#39;;
private $salary = 0;
public function __construct( $name, $position, $salary ) {
$this->name = $name;
$this->position = $position;
$this->salary = $salary;
}
public function getInfo() {
$return = "姓名:".$this->name."\t";
$return .= "职位:".$this->position."\t";
$return .= "薪水:".$this->salary."\n";
return $return;
}
}
class Leaf extends Corp{
}
class Branch extends Corp{
private $subordinateList = array();
public function addSubordinate(Corp $corp){
array_push($this->subordinateList, $corp);
}
public function getSubordinateList(){
return $this->subordinateList;
}
}
$root = new Branch(&#39;马总&#39;,&#39;总经理&#39;,100000);
$branch1 = new Branch(&#39;罗总&#39;,&#39;研发部门经理&#39;,20000);
$branch2 = new Branch(&#39;高总&#39;,&#39;销售部门经理&#39;,80000);
$leaf1 = new Leaf(&#39;张三&#39;,&#39;开发人员&#39;,7000);
$leaf2 = new Leaf(&#39;李四&#39;,&#39;开发人员&#39;,8000);
$leaf3 = new Leaf(&#39;二蛋&#39;,&#39;销售人员&#39;,10000);
$leaf4 = new Leaf(&#39;狗子&#39;,&#39;销售人员&#39;,15000);
$root->addSubordinate($branch1);
$branch1->addSubordinate($leaf1);
$branch1->addSubordinate($leaf2);
$root->addSubordinate($branch2);
$branch2->addSubordinate($leaf3);
$branch2->addSubordinate($leaf4);
function getTreeInfo($branch){
echo $branch->getInfo();
$subordinateList = $branch->getSubordinateList();
foreach ($subordinateList as $value) {
if($value instanceof Branch){
getTreeInfo($value);
}else{
echo $value->getInfo();
}
}
}
getTreeInfo($root);
?>
Copy after login

Running results:

Name: Mr. Ma Position: General Manager Salary: 100000

Name: Mr. Luo Position: R&D Department Manager Salary: 20000

Name: Zhang San Position: Developer Salary: 7000

Name: Li Si Position: Developer Salary: 8000

Name: Mr. Gao Position: Sales Department Manager Salary: 80000

Name: Erdan Position: Salesperson Salary: 10000

Name: Gouzi Position: Salesperson Salary: 15000

[Finished in 0.1s]

Definition of combination mode

combination mode is also called synthesis mode, also called part-whole mode, It is mainly used to describe the relationship between parts and the whole. It is defined as: combining objects into a tree structure to represent the "part-whole" hierarchical structure, so that users can use single objects and combined objects consistently. The combination mode is mainly composed of three roles

1. Component abstract component role

Define the common methods and properties of the combined objects. You can define some default behaviors or properties, such as the Corp class in the example.

2. Leaf component

3. Composite branch component

Combine branch nodes and leaf nodes to form a tree structure

Advantages of combination mode

1. Simple calling of high-level modules

In a tree-shaped structure All nodes are Components, and there is no difference between the part and the whole for the caller. That is to say, the high-level module does not have to care whether it is dealing with a single object or the entire combined structure, which simplifies the code of the high-level module.

2. The node can be added by itself

Just find its parent node. It is very easy to expand and complies with the opening and closing principle.

Disadvantages of the combination mode

The combination mode has a very obvious shortcoming. See the definition in the scene class, did you mention the definition when using leaves and branches? The implementation class is used directly! This is very inappropriate in interface-oriented programming, conflicts with the dependency delegation principle, and limits the scope of influence in the interface.

Usage scenarios of combination mode

1. Scenarios for maintaining and displaying part-whole relationships, such as tree menu, file, and folder management.

2. Scenarios where total price modules or functions can be independently separated from a whole.

Notes on the combination mode

As long as it is a tree structure, you must consider using the combination mode. This must be remembered, as long as it is to reflect the relationship between the part and the whole, and this relationship may be relatively deep. , you should consider the combination model.

Extension of combination mode

1. Real combination mode (skip)

2. Transparent combination mode

The example is a safe combination mode. The transparent mode puts the methods used for combination into abstract classes (Skip)

3. Combination mode traversal

In the example, the tree is traversed from the upper level to the lower level. If a leaf node is randomly selected, how to traverse to the upper level?

Tree-like composite pattern

It’s actually very simple. Just set its parent node when adding a node. The code is as follows:

<?php
abstract class Corp {
private $name = &#39;&#39;;
private $position = &#39;&#39;;
private $salary = 0;
<strong>private $parent = null;</strong>
public function __construct( $name, $position, $salary ) {
$this->name = $name;
$this->position = $position;
$this->salary = $salary;
}
public function getInfo() {
$return = "姓名:".$this->name."\t";
$return .= "职位:".$this->position."\t";
$return .= "薪水:".$this->salary."\n";
return $return;
}
<strong>public function setParent($parent){
$this->parent = $parent;
}
public function getParent(){
return $this->parent;
}</strong>
}
class Leaf extends Corp{
}
class Branch extends Corp{
private $subordinateList = array();
public function addSubordinate(Corp $corp){
<strong>$corp->setParent($this);</strong>
array_push($this->subordinateList, $corp);
}
public function getSubordinateList(){
return $this->subordinateList;
}
}
$root = new Branch(&#39;马总&#39;,&#39;总经理&#39;,100000);
$branch1 = new Branch(&#39;罗总&#39;,&#39;研发部门经理&#39;,20000);
$branch2 = new Branch(&#39;高总&#39;,&#39;销售部门经理&#39;,80000);
$leaf1 = new Leaf(&#39;张三&#39;,&#39;开发人员&#39;,7000);
$leaf2 = new Leaf(&#39;李四&#39;,&#39;开发人员&#39;,8000);
$leaf3 = new Leaf(&#39;二蛋&#39;,&#39;销售人员&#39;,10000);
$leaf4 = new Leaf(&#39;狗子&#39;,&#39;销售人员&#39;,15000);
$root->addSubordinate($branch1);
$branch1->addSubordinate($leaf1);
$branch1->addSubordinate($leaf2);
$root->addSubordinate($branch2);
$branch2->addSubordinate($leaf3);
$branch2->addSubordinate($leaf4);
function getParentInfo($leaf){
echo $leaf->getInfo();
$parent = $leaf->getParent();
if($parent instanceof branch)
getParentInfo($parent);
}
getParentInfo($leaf4);
?>
Copy after login

Run results:

Name: Gouzi Position: Salesperson Salary: 15000

Name: Mr. Gao Position: Sales Department Manager Salary: 80000

Name: Mr. Ma Position: General Manager Salary: 100000

[Finished in 0.2s]

The bold part in the code is the difference from the previous example.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles