組合模式(Composite)凉翻,將對(duì)象組合成樹形結(jié)構(gòu)以表示‘部分-整體’的層次結(jié)構(gòu)了讨。組合模式使得用戶對(duì)單個(gè)對(duì)象和組合對(duì)象的使用具有一致性。
主方法
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);
}
葉子節(jié)點(diǎn)
/**
* 由于葉子沒(méi)有在增加分支和樹葉制轰,所以Add和Remove方法實(shí)現(xiàn)它沒(méi)有意義量蕊,
* 但這樣做可以消除葉子節(jié)點(diǎn)和枝節(jié)點(diǎn)在抽象層次的區(qū)別,它們具備完全一致的接口
*/
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);
}
}
樹枝節(jié)點(diǎn)
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);
}
}
}