Design Patterns – Composite Patterns

Scene

Write a program to display the departmental structure of a school:

It is necessary to display the school’s departmental composition on one page. A school has multiple colleges. A college has multiple departments.

Manage multiple objects as a tree structure

Traditional solutions solve existing problems

(1) Think of colleges as subcategories of schools, and departments as subcategories of colleges. This is actually based on the size of the organization for hierarchy

(2) The actual requirement is: display the school’s departments on one page. A school has multiple colleges and a college has multiple departments. Therefore, this solution cannot implement management operations well, such as adding colleges and departments. delete traversal etc.

(3) Solution: Think of schools, colleges and departments as organizational structures. There is no inheritance relationship between them, but a tree structure, which can better realize management operations.

Introduction

(1) Composite Pattern (Composite Pattern), also known as partial overall pattern, creates a tree structure of object groups and combines objects into a tree structure to represent; the hierarchical relationship of “whole-part”

(2) The combination mode combines objects according to the tree structure, which is used to represent the part and the whole level

(3) This type of design pattern is a structural pattern

(4) The combination mode enables users to have consistent access to individual objects and combined objects, that is: combination allows customers to handle individual objects and combined objects in a consistent manner

Problems Solved by Combination Mode

When the object we want to process can generate a tree structure and we want to operate on the nodes and leaves on the tree, it can provide a consistent way without considering whether it is a node or a leaf

Code Demo

Create topmost abstract class

@Data
public abstract class OrganizationComponent {
    //name
    private String name;

    //illustrate
    private String des;

    protected void add(OrganizationComponent org){
        // default implementation
        throw new UnsupportedOperationException();
    }

    protected void remove(OrganizationComponent org){
        // default implementation
        throw new UnsupportedOperationException();
    }

    //method print sets abstract subclasses need to implement this method
    protected abstract void print();

    public OrganizationComponent(String name, String des) {
        this.name = name;
        this.des = des;
    }
}

school subclass implementation

public class University extends OrganizationComponent {

    //polymerization
    List<OrganizationComponent> orgs = new ArrayList<>();

    @Override
    protected void add(OrganizationComponent org) {
        orgs. add(org);
    }

    @Override
    protected void remove(OrganizationComponent org) {
        orgs. remove(org);
    }

    /**
     * The print method is to directly input the colleges included in UNiversity
     */
    @Override
    protected void print() {
        System.out.println("=============== " + getName() + " ==================");
        // traverse orgs
        orgs.forEach(item->item.print());

    }

    public University(String name, String des) {
        super(name, des);
   }

    @Override
    public String getName() {
        return super. getName();
    }

    @Override
    public String getDes() {
        return super. getDes();
    }

    @Override
    public void setName(String name) {
        super. setName(name);
    }

    @Override
    public void setDes(String des) {
        super. setDes(des);
    }
}

Faculty subclass implementation

public class College extends OrganizationComponent {
    //polymerization
    List<OrganizationComponent> orgs = new ArrayList<>();

    @Override
    protected void add(OrganizationComponent org) {
        orgs. add(org);
    }

    @Override
    protected void remove(OrganizationComponent org) {
        orgs. remove(org);
    }

    /**
     * The print method is to directly input the colleges included in UNiversity
     */
    @Override
    protected void print() {
        System.out.println("=============== " + getName() + " ==================");
        // traverse orgs
        orgs.forEach(item->item.print());
    }


    public College(String name, String des) {
        super(name, des);
    }

    @Override
    public String getName() {
        return super. getName();
    }

    @Override
    public String getDes() {
        return super. getDes();
    }

    @Override
    public void setName(String name) {
        super. setName(name);
    }

    @Override
    public void setDes(String des) {
        super. setDes(des);
    }
}

Department subclass implementation

public class Department extends OrganizationComponent{


    @Override
    protected void print() {
        System.out.println("=============== " + getName() + " ==================");
        System.out.println(getName());
    }

    public Department(String name, String des) {
        super(name, des);
    }

    @Override
    public String getName() {
        return super. getName();
    }

    @Override
    public String getDes() {
        return super. getDes();
    }

    @Override
    public void setName(String name) {
        super. setName(name);
    }

    @Override
    public void setDes(String des) {
        super. setDes(des);
    }
}

test

 public static void main(String[] args) {
        //Create objects from big to small School->College->Department
        //Create a school
        OrganizationComponent university = new University("Wuhan University","China's first-class university");
        //create college
        OrganizationComponent computeCpllege = new College("Computer College","Computer Department");
        OrganizationComponent softwareCollege = new College("Software College","Computer Department");
        //Create the departments (professionals) under each college
        computeCpllege.add(new Department("Software Engineering","Software Engineering is good"));
        computeCpllege.add(new Department("Electronic Information Science", "Electronic Information Network Data"));
        computeCpllege.add(new Department("Computer Science and Technology", "A major that many people like to apply for"));
        softwareCollege.add(new Department("Software Technology","There are many girls majoring in software technology"));
        softwareCollege.add(new Department("Communication Engineering", "Communication requires learning hardware"));

        //add the college to the school
        university.add(computeCpllege);
        university. add(softwareCollege);

        System.out.println("All school information");
        university. print();
        System.out.println("Separation line ----------------------------------------- -------------->");
        System.out.println("All information of School of Computer Science");
        computeCpllege. print();
        System.out.println("Separation line ----------------------------------------- -------------->");


    }

Precautions and details of composite mode

(1) Simplify the operation of the client. The client only needs to face the consistent object without considering the whole part or the node leaf

(2) It has strong scalability. When we want to change the combined object, we only need to adjust the internal hierarchical relationship, and the client does not need to make any changes.

(3) It is convenient to create a complex hierarchical structure. The client does not need to care about the composition details in the combination. It is easy to adjust the price of nodes or leaves to create a complex tree structure.

(4) When it is necessary to traverse the organizational structure or the processed objects have a tree structure, it is very suitable to use the combination mode

(5) High abstraction is required. If there are many differences between nodes and leaves, for example, many methods and attributes are different, it is not suitable to use the combination mode