sheng's learning notes - Design Pattern - combination pattern

schematic diagram

Definition of Composite Pattern: sometimes called part whole pattern, it is a pattern that combines objects into a tree hierarchy, which is used to represent the "whole part" relationship, so that users have consistent access to single objects and composite objects. It belongs to structural type Design pattern.

Composite is easy to understand. When you think of composite, you should think of tree structure diagram. These objects in the assembly have common interfaces. When the method of an object in the assembly is called and executed, the composite will traverse the whole tree structure, find the object that also contains this method, and implement the call and execution. It can be described as pulling a hundred.

The combination mode is generally used to describe the relationship between the whole and part. It organizes objects into a tree structure. The top-level node is called the root node. The root node can contain branch nodes and leaf nodes, and the branch node can contain branch nodes and leaf nodes. The tree structure diagram is as follows

Composite benefits:
1. Make the client call simple. The client can consistently use the composite structure or a single object, so the user does not have to deal with a single object or the whole composite structure, which simplifies the client code.
2. It is easier to add object parts to the assembly. The client does not have to change the code because a new object part is added.


package design.composite;

//Abstract component
public interface Component {
    public void add(Component c);

    public void remove(Component c);

    public Component getChild(int i);

    public void operation();

    public float calcSales();
package design.composite;

import java.util.ArrayList;
import java.util.List;

public class Employee implements Component {

    // name
    private String name;

    // department
    private String dept;

    // salary
    private int salary;

    // Subordinate list
    private List<Component> subordinates;

    public Employee(String name, String dept, int sal) { = name;
        this.dept = dept;
        this.salary = sal;
        subordinates = new ArrayList<Component>();

    public void add(Component c) {

    public void remove(Component c) {

    public Component getChild(int i) {
        return subordinates.get(i);

    public void operation() {
        for (Object obj : subordinates) {
            ((Component) obj).operation();

    public float calcSales() {
        float s = this.salary;
        for (Object obj : subordinates) {
            s += ((Component) obj).calcSales();
        return s;

    public String toString() {
        return ("Employee :[ Name : " + name
                + ", dept : " + dept + ", salary :"
                + salary + " ]");
package design.composite;

 * Definition of Composite Pattern: sometimes called part whole pattern,
 * It is a mode of combining objects into a tree hierarchy, which is used to represent the "whole part" relationship,
 * It enables users to have consistent access to single objects and composite objects, which belongs to structural design pattern.
 * <p>
 * In real life, there are many "part whole" relationships, such as departments and colleges in universities, departments and branches in head offices, books and schoolbags in school supplies
 * The same is true in software development, such as files and folders in the file system, simple controls and container controls in form programs, etc.
 * The processing of these simple objects and composite objects will be very convenient if they are implemented in combination mode.
 * <p>
 * For example, there are two principals under the CEO (belonging to the sales and marketing departments respectively), and there are also two employees under each principal, forming the following tree structure
 * Everyone is a node and can have subordinates
 * John(CEO)
 * Robert(Head Sales)                              Michel(Head Marketing)
 * Richard(Sales)       Rob(Sales)              Laura(Marketing)     Bob(Marketing)

public class CompositePattern {
    public static void main(String[] args) {
        Employee CEO = new Employee("John", "CEO", 30000);

        Employee headSales = new Employee("Robert", "Head Sales", 20000);

        Employee headMarketing = new Employee("Michel", "Head Marketing", 20000);

        Employee clerk1 = new Employee("Laura", "Marketing", 10000);
        Employee clerk2 = new Employee("Bob", "Marketing", 10000);

        Employee salesExecutive1 = new Employee("Richard", "Sales", 10000);
        Employee salesExecutive2 = new Employee("Rob", "Sales", 10000);




        // According to the organizational relationship of the CEO, find all the child node information according to the root node
        // Calculate the salary of all subordinates of the CEO
        System.out.println("sales sum:" + CEO.calcSales());

Operation results:

Employee :[ Name : John, dept : CEO, salary :30000 ]
Employee :[ Name : Robert, dept : Head Sales, salary :20000 ]
Employee :[ Name : Richard, dept : Sales, salary :10000 ]
Employee :[ Name : Rob, dept : Sales, salary :10000 ]
Employee :[ Name : Michel, dept : Head Marketing, salary :20000 ]
Employee :[ Name : Laura, dept : Marketing, salary :10000 ]
Employee :[ Name : Bob, dept : Marketing, salary :10000 ]
sales sum:110000.0

[example 1] the combination mode is used to realize the function of displaying the information of the selected goods and calculating the total price of the selected goods after the user purchases in the store.

Note: if Mr. Li goes to Shaoguan "Tianjie e Jiao" daily necessities store for shopping, he uses a small red bag to pack 2 packages of Wuyuan specialties (unit price 7.9 yuan) and 1 Wuyuan map (unit price 9.9 yuan); Two packages of Shaoguan fragrant tea (unit price 68 yuan) and three packages of Shaoguan black tea (unit price 180 yuan) were packed in a small white bag; A small red bag in front and a Jingdezhen porcelain (unit price 380 yuan) were packed in a medium bag; The front middle bag, small white bag and a pair of Li Ning Sports shoes (unit price 198 yuan) are packed in a large bag.

Finally, the contents of the "big bag" include: {1 pair of Li Ning brand sports shoes (unit price 198 yuan), small white bag {2 bags of Shaoguan mushroom (unit price 68 yuan), 3 bags of Shaoguan black tea (unit price 180 yuan)}, medium bag {1 Jingdezhen porcelain (unit price 380 yuan), small red bag {2 bags of Wuyuan specialty (unit price 7.9 yuan), 1 Wuyuan map (unit price 9.9 yuan)}}, Now it is required to program and display all the commodity information put by Mr. Li in the big bag and calculate the total price to be paid.

Implementation diagram:

Reference article:

Combination mode | rookie tutorial

Combination mode (detailed version)

Tags: Java Design Pattern

Posted on Sat, 02 Oct 2021 14:05:26 -0400 by neorunner