(2) Structural pattern: 4. Composite Pattern (C++ example)

Table of contents

1. Meaning of Composite Pattern

2. Combination mode application scenarios

3. Advantages and Disadvantages of Combination Model

4. UML diagram learning of combination mode

5. A simple example of implementing the combination mode in C++ (the company's OA system)


1. Meaning of Composite Pattern

The Composite Pattern, also called the Part-whole pattern, is used to treat a group of similar objects as a single object. The composition mode combines objects according to a tree structure, which is used to represent part and whole hierarchies. This type of design pattern is a structural pattern, which creates a tree structure of groups of objects.


Compose objects into tree structures to represent part-whole hierarchies.Composite lets clients treat individual objects and compositions of objects uniformly. Used consistently. (From "Zen of Design Patterns")

2. Combination mode application scenarios

(1) When you find that the requirements reflect the hierarchical structure of parts and wholes, such as file systems, view trees, company organizational structures, etc.;

(2) When you hope that users can ignore the difference between combined objects and single objects and use all objects in the combined structure uniformly, you can consider the combination mode;

3. Advantages and Disadvantages of Combination Model

(1) Advantages:

1) Simplify client code : The combination mode allows the client to treat single objects and composite objects uniformly without distinguishing their types, thus simplifying the client code.

2) Flexibility and scalability : Through the combination mode, the structure of objects can be dynamically added, deleted, and modified, making the system more flexible and easy to expand.

3) Unified operation interface : The combination mode defines a unified operation interface, allowing the client to process single objects and combined objects consistently without caring about the type of specific objects.

4) Conveniently create complex object structures : The combination mode can organize objects into a tree structure, making it easy to create and manage complex object structures.

(2) Disadvantages:

1) Increased design complexity : Using the combination pattern will introduce more classes and objects, thereby increasing the design complexity of the system. This may result in a complex code structure that is difficult to understand and maintain.

2) Not suitable for all scenarios : Combination mode is suitable for situations where whole-part hierarchies are represented, but not all situations are suitable for using combination mode. If there is no obvious hierarchical relationship between objects or there is no need to treat single objects and composite objects uniformly, then using the composition pattern may bring unnecessary complexity.

3) Difficulty restricting component types : In composition mode, composition objects can contain other composition objects or leaf objects. This means that it is difficult to enforce type constraints on components at compile time, which can lead to some runtime errors.

4) Possible performance loss : Since the combination mode involves recursively traversing the entire object tree, it may cause some performance loss. Especially when the object tree is very large, the traversal operation may consume more time and resources.

Although the composition pattern has some disadvantages, it is still a powerful and commonly used design pattern, especially suitable for scenarios where you need to deal with hierarchical structures. When using the composition pattern, you need to weigh its advantages and disadvantages based on your specific needs and system design, and ensure that the pattern is applied appropriately.

4. UML diagram learning of combination mode

Composition elements:

(1) Abstract component role (Composite): It is the declaration interface of the objects in the composition and implements the default behavior of the interface common to all classes.

(2) Leaf component role (Leaf): The single object mentioned above, the leaf node has no child nodes.

(3) Branch component role (Composite): Define the behavior of the composite component with subcomponents, store the subcomponents, and implement operations related to the subcomponents in the Component interface.

(4) Client (Client): object using Component components.

5. A simple example of implementing the combination mode in C++ (the company's OA system)

#include <iostream>
#include <string>
#include <vector>

// 组件接口
class Component 
{
public:
	virtual void display() const = 0;
};

// 叶子对象:员工
class Employee : public Component 
{
private:
	std::string name;

public:
	Employee(const std::string& name) : name(name) {}

	void display() const override 
	{
		std::cout << "Employee: " << name << std::endl;
	}
};

// 组合对象:部门
class Department : public Component 
{
private:
	std::string name;
	std::vector<Component*> members;

public:
	Department(const std::string& name) : name(name) {}

	void add(Component* member) 
	{
		members.push_back(member);
	}

	void remove(Component* member) 
	{
		// 在实际应用中可能需要更复杂的逻辑来删除成员
		members.erase(std::remove(members.begin(), members.end(), member), members.end());
	}

	void display() const override 
	{
		std::cout << "Department: " << name << std::endl;
		for (const auto& member : members) 
		{
			member->display();
		}
	}
};

int main() 
{
	// 创建公司的组织结构
	Department company("Company");

	Department department1("Department 1");
	Employee employee1("Employee 1");
	Employee employee2("Employee 2");

	Department department2("Department 2");
	Employee employee3("Employee 3");
	Employee employee4("Employee 4");

	// 构建组织结构
	company.add(&department1);
	company.add(&department2);

	department1.add(&employee1);
	department1.add(&employee2);

	department2.add(&employee3);
	department2.add(&employee4);

	// 显示公司的组织结构
	company.display();

	return 0;
}

In the above example, we created a Component interface as the base class of the component, which contains a display method. The Employee class represents leaf objects and the Department class represents composite objects. A vector is used in the Department class to store members.

In the main function, we create a company object company and two department objects department1 and department2, as well as four employee objects employee1, employee2, employee3 and employee4. Then, add departments and employees to the company's organizational structure. Finally, calling the display method of company will recursively display the organizational structure of the entire company.

Running the above code, the output will be:

Department: Company

Department: Department 1

Employee: Employee 1

Employee: Employee 2

Department: Department 2

Employee: Employee 3

Employee: Employee 4

As you can see, the display method of the composite object successfully calls the display method of all subcomponents recursively, thus displaying the company's organizational structure.

Through the combination mode, we can manage and operate the company's organizational structure in a unified way, thus simplifying the use and maintenance of the code.

Guess you like

Origin blog.csdn.net/bigger_belief/article/details/132299051