This is the fourth day of my participation in the August More text Challenge. For details, see:August is more challenging

I. What is the combination mode?

The composition pattern defines how to recursively combine container objects and leaf objects so that customers can use them consistently without distinguishing between container objects and leaf objects.

The composite pattern represents a “whole-part” hierarchy of structures by combining multiple objects to form a tree structure.

The combination pattern has consistency for single objects (leaf objects) and composite objects (composite objects). It organizes objects into a tree structure, which can be used to describe the relationship between whole and parts. It also obfuscates the concept of simple elements (leaf objects) and complex elements (container objects), allowing the client to treat complex elements as if they were simple elements, thus enabling the client to decouple from the internal structure of complex elements.

What does that mean? Take a look at the images below:

Now you have folders, and you can have files and folders under folders. So this recursive call, if we split it up, the file can be viewed as a leaf node, and the folder can be viewed as a container. There are also files and folders under the folder container. The relationship between them is implemented using the composite pattern.

The key to the composition pattern is to design an abstract composition class that represents both composition objects and leaf objects. The advantage of this is that the client does not need to distinguish between a composite object and a leaf object, but simply treats it as a composite object.

Structure and case of combination pattern

Example 1: File structure

Let’s look at how to implement the file structure. Let’s start with a UML diagram:

First of all, define an abstract class File, and then a single concrete File and folder to implement the abstract File interface, in the folder interface there is a collection of storing abstract files. Realized the combination of files and folders.

Code implementation:

  1. Abstract file interface
package com.lxl.www.designPatterns.compositePattern.files;

/** * Abstract file interface */
public abstract class File {
    protected String name;

    public File(String name) {
        this.name = name;
    }

    public abstract void show(a);
}

Copy the code
  1. The specific file

Text file

package com.lxl.www.designPatterns.compositePattern.files;

public class TextFile extends File {
    public TextFile(String name) {
        super(name);
    }

    @Override
    public void show(a) {
        System.out.println("This is the text file displayed at ----."); }}Copy the code

Image files

package com.lxl.www.designPatterns.compositePattern.files;

public class ImageFile extends File {
    public ImageFile(String name) {
        super(name);
    }

    @Override
    public void show(a) {
        System.out.println("This is the picture file shown at ----."); }}Copy the code

Audio file

package com.lxl.www.designPatterns.compositePattern.files;

public class AudioFile extends File {
    public AudioFile(String name) {
        super(name);
    }

    @Override
    public void show(a) {
        System.out.println("This is the audio file shown at ----."); }}Copy the code

Video file

package com.lxl.www.designPatterns.compositePattern.files;

public class VideoFile extends File {
    public VideoFile(String name) {
        super(name);
    }

    @Override
    public void show(a) {
        System.out.println("Here's the video file shown at ----."); }}Copy the code
  1. folder
package com.lxl.www.designPatterns.compositePattern.files;

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

public class Folder extends File{

    List<File> files = new ArrayList<File>();

    public Folder(String name) {
        super(name);
    }

    public void addFile(File file) {
        files.add(file);
    }

    public void delFile(File file) {
        files.remove(file);
    }

    @Override
    public void show(a) {
        System.out.println("This is a" + this.name + "-- show");
        for(File file: this.files) { file.show(); }}}Copy the code
  1. The client client
package com.lxl.www.designPatterns.compositePattern.files;

public class Client {
    public static void main(String[] args) {
        File text1 = new TextFile("TXT file");
        File image1 = new ImageFile("Image Type Files");
        File audio1 = new AudioFile("Audio file");
        File video1 = new VideoFile("Video file");


        Folder folder = new Folder("First-class folder");
        folder.addFile(text1);
        folder.addFile(image1);
        folder.addFile(audio1);
        folder.addFile(video1);

        Folder folder2 = new Folder("Secondary folder");
        folder.addFile(folder2);

        File text2 = new TextFile("TXT file 2");
        File image2 = new ImageFile("Image Type File 2");
        File audio2 = new AudioFile("Audio file 2");
        File video2 = new VideoFile("Video File 2"); folder2.addFile(text2); folder2.addFile(image2); folder2.addFile(audio2); folder2.addFile(video2); folder.show(); }}Copy the code
  1. The results

Finally, what we get when we run the program is

This is a level 1 folder —- shown

This is a text file – the show This is image file – show This is an audio file, display This is video file, display This is a secondary folders – show This is a text file – the show This is image file – show This is an audio file, display This is video file, display

The final display of the file is as follows:

Case 2: Organizational structure

Let’s start with the UML diagram:

In this case, there are usually many departments under the company, and sub-departments are set under the departments. The organizational structure is as follows:

Let’s look at the code implementation step one: the department abstract interface

/** * Department */
public interface Department {

    /** * Execute work */
    void show(a);
}
Copy the code

Step 2: Leaf department, no other department below

package com.lxl.www.designPatterns.compositePattern.company;

/** * leaves the department, that is, there are no other departments under the department */
public class LeafDepartment implements Department{
    /** * Department name */
    private String name;
    public LeafDepartment(String name) {
        this.name = name;
    }

    @Override
    public void show(a) {
        System.out.println(this.name); }}Copy the code

Step 3: Aggregate departments, that is, there are sub-departments below

package com.lxl.www.designPatterns.compositePattern.company;

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

/** * Aggregate division -- that is, there are other divisions */
public class AggregateDepartmen implements Department{

    /** Department name */
    private String name;

    private List<Department> departments = new ArrayList<>();

    public  AggregateDepartmen(String name) {
        this.name = name;
    }

    public void addDepartment(Department department) {
        departments.add(department);
    }

    public void delDepartment(Department department) {
        departments.remove(department);
    }


    @Override
    public void show(a) {
        System.out.println(this.name + "And under the banner." + departments.size() + "Sub-departments");
        for(Department department: departments) { department.show(); }}}Copy the code

Step 4: Client invocation

package com.lxl.www.designPatterns.compositePattern.company;

/** * Corporate department client */
public class Client {
    public static void main(String[] args) {
        AggregateDepartmen company = new AggregateDepartmen("The company");

        Department fawu = new LeafDepartment("Department of Justice");
        Department xingzheng = new LeafDepartment("Administration Department");
        Department renshi = new LeafDepartment("Personnel Department");
        AggregateDepartmen jishu = new AggregateDepartmen("Technical Department");

        Department java = new LeafDepartment("Java Division");
        Department c = new LeafDepartment("C++ business unit");
        Department go = new LeafDepartment("GO Division");
        Department front = new LeafDepartment("Big Front End Business Division"); company.addDepartment(fawu); company.addDepartment(xingzheng); company.addDepartment(renshi); company.addDepartment(jishu); jishu.addDepartment(java); jishu.addDepartment(c); jishu.addDepartment(go); jishu.addDepartment(front); company.show(); }}Copy the code

Step 5: Run the results

The company has four sub-departments: legal department, administration department, human resources department, technology department, and four sub-departments: Java division, C++ division, GO division, and big front-end divisionCopy the code

By combining patterns, we have mapped out the organizational structure of a company, and even more complex architectures can be implemented this way.

Iii. Usage scenarios of composite mode

The combination pattern is very common in our daily life, such as the structure of relationships in the organizational structure of a company. The relationship between the head office and branch office is analyzed in the following application scenarios.

  1. Where it is necessary to represent a hierarchy of whole and parts of an object.
  2. Where the difference between a composite object and a single object is hidden from the user and all objects in the composite structure can be used with a unified interface.

Four. The advantages and disadvantages of combination mode

advantages

  1. Allow the client to operate in a uniform way, without distinguishing between composite objects and leaf objects
  2. High level module calls are simple.
  3. Free node increase

disadvantages

The application of the six principles of design mode by combination mode.

  1. Single responsibility principle: an interface does only one thing – conform
  2. Rule of substitution: subclass substitution can be used wherever the superclass appears, here the superclass method is an interface — conform
  3. Interface isolation rule: Minimum interface. Do not have fat interfaces
  4. Inverted dependency principle: Program to interfaces, not to specifics — yes
  5. Demeter’s law: relate to the least number of objects – conform
  6. Open closed principle: Open for modification, closed for extension – compliant