Java Implementation Composite Pattern
Composite pattern is a structural design pattern that aims to represent the overall/partial hierarchical relationship by combining objects into a tree structure, so that users have consistency in their use of individual and composite objects. This pattern is used to organize a group of objects into a Tree structure and treat them in a unified way.
Applicable scenario:
When you need to organize objects into a tree structure and want to unify the processing of individual and composite objects, you can use the composite mode.
When you want the client to ignore the differences between composite objects and individual objects, you can use composite mode.
Benefits:
1. Make the client code more concise, without the need to distinguish between handling individual objects and composite objects.
2. New components can be flexibly added, as the composite pattern unifies objects into composite objects and individual objects.
The following is an example code for implementing composite patterns using the Java language:
//Abstract components in composite patterns
interface Component {
void operation();
}
//Leaf component
class Leaf implements Component {
private String name;
public Leaf(String name) {
this.name = name;
}
public void operation() {
System.out.println("Leaf [" + name + "] is performing operation.");
}
}
//Container components
class Composite implements Component {
private List<Component> children = new ArrayList<>();
public void add(Component component) {
children.add(component);
}
public void remove(Component component) {
children.remove(component);
}
public void operation() {
System.out.println("Composite is performing operation.");
for (Component component : children) {
component.operation();
}
}
}
//Client code
public class Client {
public static void main(String[] args) {
//Creating Components
Leaf leaf1 = new Leaf("leaf1");
Leaf leaf2 = new Leaf("leaf2");
Leaf leaf3 = new Leaf("leaf3");
Composite composite1 = new Composite();
Composite composite2 = new Composite();
//Combine into a tree structure
composite1.add(leaf1);
composite1.add(leaf2);
composite2.add(leaf3);
composite1.add(composite2);
//Calling the operation of a composite object
composite1.operation();
}
}
In the above example code, the Component interface defines a unified operation method, which is implemented by the Leaf class and the Composite class respectively, representing leaf components and container components. Sub components can be added or removed in container components, and the operation methods of sub components can be recursively called. Finally, the client code uses composite patterns to create components with a tree structure and calls the operation methods of the root component.