一、简介
组合模式(Composite Pattern),将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
在对象关系之间存在上下层级结构时使用,可以忽略组合对象和单个对象的不同,统一地使用组合结构中的所有对象。
基本对象可以被组合成更复杂的组合对象,而这个组合对象又可以被组合,这样就可以递归下去。
二、结构图
Component:组合中的对象声明接口,在适当情况下,实现所有类公共接口的默认行为。声明一个接口用于访问和管理Component的子部件。
Leaf:在组合中表示叶节点对象,叶节点没有子节点。
Composite:定义有枝节点行为,用于存储子部件,在Component中实现与子部件有关的操作,比如增加、删除。
三、代码实现
1.Component
public abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
public abstract void add(Component component);
public abstract void remove(Component component);
public abstract void display(int depth);
public String getSpace(int depth) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < depth; i++) {
stringBuilder.append("-");
}
return stringBuilder.toString();
}
}
2.Leaf
public class Leaf extends Component{
public Leaf(String name) {
super(name);
}
@Override
public void add(Component component) {
System.out.println("can not add to a leaf");
}
@Override
public void remove(Component component) {
System.out.println("can not remove a leaf");
}
@Override
public void display(int depth) {
System.out.println(getSpace(depth) + name);
}
}
3.Composite
public class Composite extends Component{
private List<Component> components = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override
public void add(Component component) {
components.add(component);
}
@Override
public void remove(Component component) {
components.remove(component);
}
@Override
public void display(int depth) {
System.out.println(getSpace(depth) + name);
components.stream().forEach(component -> component.display(depth + 1));
}
}
4.Client:测试类
public class Client {
public static void main(String[] args) {
Composite root = new Composite("root");
root.add(new Leaf("A"));
root.add(new Leaf("B"));
Composite comp = new Composite("X");
comp.add(new Leaf("Leaf XA"));
comp.add(new Leaf("Leaf XB"));
Composite comp2 = new Composite("Y");
comp2.add(new Leaf("Leaf YA"));
comp2.add(new Leaf("Leaf YB"));
comp.add(comp2);
root.add(comp);
root.display(1);
}
}
5.测试结果
-root
--A
--B
--X
---Leaf XA
---Leaf XB
---Y
----Leaf YA
----Leaf YB