组合模式(Composite),将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
主方法
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 comp = new Composite("Composite X");
comp.Add(new Leaf("Leaf XA"));
comp.Add(new Leaf("Leaf XB"));
root.Add(comp);
Composite comp2 = new Composite("Composite XY");
comp2.Add(new Leaf("Leaf XYA"));
comp2.Add(new Leaf("Leaf XYB"));
comp.Add(comp2);
root.Add(new Leaf("Leaf C"));
Leaf leaf = new Leaf("Leaf D");
root.Add(leaf);
root.Remove(leaf);
root.Display(1);
}
}
声明接口
public 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 Display(int depth);
}
叶子节点
/**
* 由于叶子没有在增加分支和树叶,所以Add和Remove方法实现它没有意义,
* 但这样做可以消除叶子节点和枝节点在抽象层次的区别,它们具备完全一致的接口
*/
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
public void Add(Component c) {
System.out.println("Canno add to a leaf");
}
public void Remove(Component c) {
System.out.println("Cannot remove from a leaf");
}
public void Display(int depth) {
String result = name;
for (int i = 0; i < depth; i++) {
result = '-' + result;
}
System.out.println(result);
}
}
树枝节点
import java.util.ArrayList;
import java.util.List;
public class Composite extends Component {
private List<Component> children = new ArrayList<Component>();
public Composite(String name) {
super(name);
}
public void Add(Component c) {
children.add(c);
}
public void Remove(Component c) {
children.remove(c);
}
public void Display(int depth) {
String result = name;
for (int i = 0; i < depth; i++) {
result = '-' + result;
}
System.out.println(result);
for (Component component : children) {
component.Display(depth + 2);
}
}
}