“This is the 22nd day of my participation in the First Challenge 2022. For details: First Challenge 2022”

Today we are going to talk about Component patterns. It needs to be emphasized that composition is not the same concept as “composition” mentioned in the bridge Pattern. The latter refers to the behavior of changing class A into class B attributes to achieve the ability of class A, while the former is A design idea of combining similar objects into A set of callable tree data structures.

Therefore, the composite mode is also called the composite mode, or part-whole mode, which is mainly used to describe the relationship between the Part and the Whole. Its purpose is to make the client have a unified response when operating the Whole and partial objects, so that the client can use the single object and the combined object in a consistent way. Finally, the complex hierarchical structure of client and object is coupled.

Let’s expand on the composition pattern.

Definition 1.

Composite pattern is a structural design pattern, which is defined as: “Objects are grouped into a tree structure to represent a” partial-whole “hierarchy, so that users can use single objects and composite objects consistently.

2. The class diagram

In combination mode, there are several roles:

  • Abstract Component roles (Component) : An abstraction of whole objects and parts, describing the unified standards that whole objects and parts have.
  • Leaf role (Leaf) : A specific component that does not contain child nodes, the smallest unit traversed in the composite pattern
  • Composite: A concrete component of a whole that contains multiple child nodes

The class diagram for the composite pattern is as follows:

Example 3.

The composite pattern is often used to solve complex scenarios of tree data structures. For example, in the ERP system, which is most commonly used by enterprises, the general business describing organizational relationships is the best practice of the composite pattern. There are many business scenarios, such as companies (head office and subsidiaries), departments (large departments and sub-departments), organizations (large organizations and sub-organizations), employees (department heads and department employees), and so on.

Here we take the organization as an example to say the application of combination mode in ERP system. Demand is this: in the organizational structure of a company, usually below the company will to business department as the unit is divided into multiple organizations, such as is responsible for the management of human resources of the company’s personnel, product research and development of the technology department is responsible for technology, and technology can be subdivided again below for the front-end and back-end department, testing department, etc., under the human resources department and can be divided into HR department, administration department, etc.

The organizational structure of a company can tell you how ambitious and ambitious it is.

All of the organizations of one of the companies mentioned above can be described by an abstract class, the abstract component role, which has the following code:

public abstract class Organization {
    /** * set of child nodes */
    protected List<Organization> children = new ArrayList<>();
    /** * Organization name */
    private String name;
    /** * Organization description */
    private String description;

    public Organization(String name, String description) {
        this.name = name;
        this.description = description;
    }

    // Abstract method: Add child nodes
    public abstract void add(Organization organization);

    // Abstract method: delete child nodes
    public abstract void remove(Organization organization);

    // Abstract method: get the child node
    public abstract void getChildren(a);


    @Override
    public String toString(a) {
        return "Organization Name:" + name + ", Organization description:"+ description; }}Copy the code

Then create the other two roles in the composite pattern, the leaf role and the branch role, with the following code:

public class ParentOrganization extends Organization {

    public ParentOrganization(String name, String description) {
        super(name, description);
    }

    @Override
    public void add(Organization organization) {
        this.children.add(organization);
    }

    @Override
    public void remove(Organization organization) {
        this.children.remove(organization);
    }

    @Override
    public void getChildren(a) {
        for (Organization organization : this.children) {
            if (organization instanceof ParentOrganization) {
                organization.getChildren();
            } else{ System.out.println(organization); }}}}public class LeafOrganization extends Organization {

    public LeafOrganization(String name, String description) {
        super(name, description);
    }

    @Override
    public void add(Organization organization) {
        throw new UnsupportedOperationException("Leaf roles are not allowed to operate add methods");
    }

    @Override
    public void remove(Organization organization) {
        throw new UnsupportedOperationException("Remove method not allowed for leaf role");
    }

    @Override
    public void getChildren(a) {
        throw new UnsupportedOperationException("The leaf role is not allowed to operate the getChildrenNumber method"); }}Copy the code

Then write the test class, first create a top-level organization, namely the head office, and then create human resources department, technology department and their subordinate departments respectively, the code is as follows:

public class Test {
    public static void main(String[] args) {
        Organization company = new ParentOrganization("Design Mode Holding Company"."An Internet company that specializes in design patterns.");

        Organization humanResource = new ParentOrganization("Human Resources department"."Responsible for managing the company's personnel.");
        Organization hr = new LeafOrganization("HR department"."In charge of recruitment");
        Organization administration = new LeafOrganization("Administration Department"."Responsible for establishing and improving work procedures, job responsibilities, etc.");
        humanResource.add(hr);
        humanResource.add(administration);

        Organization technology = new ParentOrganization("Technical Department"."Responsible for the company's technical product development");
        Organization frontend = new LeafOrganization("Front end"."Responsible for front-end development");
        Organization backend = new LeafOrganization("Back end"."Responsible for back-end development");
        Organization test = new LeafOrganization("Testing department"."Responsible for product quality assurance");
        technology.add(frontend);
        technology.add(backend);
        technology.add(test);

        // Human Resources department and Technology Department of the companycompany.add(humanResource); company.add(technology); }}Copy the code

Finally, the company to conduct some tests, the code is as follows:

public class Test {
    public static void main(String[] args) {
        System.out.println("Design Mode Holding Company under department :");
        company.getChildren();
        System.out.println("Department under human Resources Department :");
        humanResource.getChildren();
        System.out.println("Technical Sub-department :"); technology.getChildren(); }}Copy the code

The output is:

Department under the holding company: Organization Name: HR Department, Organization Description: Responsible for recruitment Organization Name: Administration Department, Organization description: Responsible for establishing and improving working procedures, job responsibilities, etc. Organization Name: Front-end Department, Organization description: Responsible for front-end development Organization Name: Back-end Department, Organization Description: Responsible for back-end development Organization Name: Testing Department, Organization Description: Responsible for product quality assurance Department under human Resources Department: Organization Name: HR Department, Organization description: Responsible for recruitment Organization Name: Administration Department, Organization Description: Responsible for the establishment and improvement of working procedures, job responsibilities and other technical Department: Organization Name: Front-end Department, Organization description: Responsible for front-end development Organization Name: Back-end Department, Organization description: responsible for back-end development Organization Name: Testing Department, Organization description: responsible for product quality assuranceCopy the code

4. Application scenarios

The usage scenarios of the composite pattern are:

  • Maintain and display partial-whole scenarios, such as tree structures, file management
  • A scenario in which some modules or functions can be separated from a whole

5. Summary

This article describes the composition pattern, which is defined as grouping objects into a tree structure to represent a partial-whole hierarchy, so that users can consistently use individual objects and composite objects.

The advantages of the combined mode are:

  • Whether organizing a single leaf node or a complex tree structure, the call is simple for the client
  • In line with the open and close principle, the expansion is very convenient, the child nodes can be added and deleted freely

The disadvantages of the combined mode are:

  • Contrary to the dependency inversion principle, the client uses leaf and branch nodes directly

6. Reference materials

  • Zen of Design Patterns (2nd Edition)

Finally, this article is included in the Personal Speaker Knowledge Base: Back-end technology as I understand it, welcome to visit.