Overview
It is a structural pattern that organizes objects in a tree structure to represent a "partial-total" hierarchy, making the client unique in the use of individual objects and combined objects.
UML class diagram
The above class diagram contains the roles:
Component: Declare a common interface for the object participating in the composition, whether it is a combination or a leaf node.
Leaf: represents a leaf node object in the combination, and the leaf node has no child nodes.
Composite: represents the object with child objects participating in the combination and gives the behavior of branch construction;
Code Example
import java.util.ArrayList;import java.util.List;abstract class Component { protected String name; public Component(String name) { this.name = name; } public abstract void Add(Component c); public abstract void Remove(Component c); public abstract void GetChild(int depth);}class Leaf extends Component { public Leaf(String name) { super(name); } @Override public void Add(Component c) { System.out.println("Can not add to a leaf"); } @Override public void Remove(Component c) { System.out.println("Can not remove from a leaf"); } @Override public void GetChild(int depth) { String temp = " "; for (int i = 0; i < depth; i++) { temp += "-"; System.out.println(temp + name); } }}class Composite extends Component { private List<Component> children = new ArrayList<>(); public Composite(String name) { super(name); } @Override public void Add(Component c) { children.add(c); } @Override public void Remove(Component c) { children.remove(c); } @Override public void GetChild(int depth) { for (Component c : children) { c.GetChild(depth); } }}public class Main { public static void main(String args[]) { Composite root = new Composite("root"); root.Add(new Leaf("Leaf A")); root.Add(new Leaf("Leaf B")); Composite compX = new Composite("Composite X"); compX.Add(new Leaf("Leaf XA")); compX.Add(new Leaf("Leaf XB")); root.Add(compX); Composite compXY = new Composite("Composite XY"); compXY.Add(new Leaf("Leaf XYA")); compXY.Add(new Leaf("Leaf XYB")); compX.Add(compXY); root.GetChild(3); }}Application scenarios
1. Requires the part-to-overall hierarchy of the object.
2. If the client wants the client to ignore the difference between a combined object and a single object, the client will use all objects in the combined structure uniformly.
Combination pattern defines a class structure composed of Leaf objects and Composite objects;
Make the client simple;
It makes it easy to add or remove sub-parts.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.