Introduction and usage of Python combination mode

1. Introduction to Python Combination Mode

Concept: Composite Pattern (Composite Pattern) is a structural design pattern that represents the "whole/part" hierarchy by combining objects into a tree structure, allowing clients to handle single objects and composite objects in the same way.

Function:

  1. Treat combined objects and leaf objects uniformly
  2. Easy to add/remove nodes
  3. Simplify client code

advantage:

  1. Nodes can be added/removed more conveniently
  2. Simplify client code without having to worry about whether to deal with individual objects or composite objects
  3. Objects and leaf objects can be flexibly combined to build a tree structure

shortcoming:

  1. If the behavior of processing nodes is inconsistent, it will lead to increased design complexity and implementation difficulty
  2. May have a certain impact on performance, because the entire tree structure needs to be traversed recursively

Application scenario:

        Applicable to situations where abstract objects form a tree structure, such as directories and files, company organizational structure, menus and menu items, etc.

How to use:

        Composite mode usually needs to define an abstract component class, which defines the common behavior of composite objects and leaf objects. At the same time, it defines the concrete classes of composite objects and leaf objects, and implements the methods in the abstract component class. A list also needs to be defined in the combined object to store child nodes.

Application in applications: For example, in a company organizational structure, the company is composed of multiple departments, and the department is composed of employees and subordinate departments, which can be represented by the combination mode. An abstract component class can be used to represent departments and employees, and concrete composite objects and leaf objects can be used to represent actual departments and employees. The client can process composite objects and leaf objects by calling methods in the abstract component class, making the client code more concise.

2. Combination mode use

working principle:

        In the composite mode, the abstract component class defines common interfaces, and the concrete composite objects and leaf objects implement these interfaces.

A composite object contains a list of subcomponents on which operations can be performed.

Clients can manipulate components by calling methods on the composite object, including adding, removing, and retrieving subcomponents.

The Composite pattern allows clients to treat individual objects and composite objects in the same way by organizing objects into a tree structure.

Example:

Suppose we want to deal with a company organizational structure, the company is composed of multiple departments, and the department is composed of employees and subordinate departments. Use the Composite pattern to represent this organizational structure.

First, define an abstract component class, which defines the public behavior of composite objects and leaf objects, here we define as Component:

Next, define a concrete composite object, a Departmentclass, defined as an object containing child nodes Component:

Then, define the leaf object, that is Employee, the class, which has no child nodes:

Finally, the client can use the composite pattern to operate, for example, to create a company organizational structure:


from abc import ABC, abstractmethod

# 定义抽象组件类
class Component():
    @abstractmethod
    def show(self):
        pass

# 定义具体组合对象, 包含子节点的Component对象
class Department(Component):
    def __init__(self, name):
        self._name = name
        self._children = []

    def add(self, component):    # 添加组件
        self._children.append(component)

    def remove(self, component): # 删除组件
        self._children.remove(component)

    def show(self):
        # print("Department show")
        print(self._name)
        for child in self._children:
            child.show()        # 实现抽象方法,显示组件

# 定义叶子节点,没有子节点
class Employee(Component):
    def __init__(self, name):
        self._name = name

    def show(self):
        # print("Employee show")
        print(self._name)      # 显示组件


# 使用组合模式,创建公司组织架构
dept1 = Department("研发部")
dept1.add(Employee("name1"))
dept1.add(Employee("name2"))
dept1.add(Employee("name0"))

dept2 = Department("财务部")
dept2.add(Employee("name3"))
dept2.add(Employee("name4"))

emp = Department("宇宙公司")
emp.add(dept1)
emp.add(dept2)

emp.show()

The output is:

Cosmos
R&D department
name1
name2
name0
Finance department
name3
name4

As can be seen from the output results, composite objects and leaf objects can be processed in the same way, and the client can use the methods in the composite object to add, delete, and display components, making the client code more concise.

Guess you like

Origin blog.csdn.net/songpeiying/article/details/131918182