1, concept,

The composition pattern groups objects into a tree structure to represent a partial-whole hierarchy. It makes the use of single objects and composite objects consistent and belongs to the structural pattern.

2. Pattern structure

  • Component: An object declaration interface in a composition that implements the default behavior of interfaces common to all classes and declares an interface for accessing and managing Component children
  • Leaf: a Leaf object that has no children
  • Composite: Container object that defines the split-point behavior used to store the child parts and implement actions related to the child parts in the Component interface

3. Application scenarios

  • Represents a partial-whole hierarchy of objects
  • Allows clients to ignore changes in different object hierarchies, and clients can program against abstract artifacts without worrying about the details of object hierarchies

4. Advantages and disadvantages

Advantages:

  • Hierarchical complex objects can be clearly defined to represent all or part of the object hierarchy, making it easier to add new artifacts
  • The client is easy to call, and clients can consistently use composite structures or individual objects within them
  • It is easier to add object artifacts to the composite body, and the client does not have to change the original code to add new object artifacts

Disadvantages:

  • When the composite pattern is used, its leaves and branches are declared as implementation classes, not interfaces, violating the dependency inversion principle
  • Make the design more abstract

5, the instance,

public abstract class File {
    private String name;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public abstract void display();
}
Copy the code
public class Folder extends File {

    private List<File> files;

    public Folder(String name) {
        super(name);
        files = new ArrayList<>();
    }

    @Override
    public void display() {
        for(File file : files) { file.display(); } } public void add(File file) { files.add(file); } public void remove(File file){ files.remove(file); }}Copy the code
public class ImageFile extends File {

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

    @Override
    public void display() {// image business logic}}Copy the code
public class TextFile extends File {

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

    @Override
    public void display() {// text business logic}}Copy the code