組合模式原理:將對象組合成樹形結構以表示“部分-整體”的層次結構。組合模式使得用戶對單個對象和組合對象的使用具有一致性。組合模式包括的成員角色有:
樹幹(Component):組合中的對象聲明接口,在適當情況下,實現所有類共有接口的默認行爲。聲明一個接口用於訪問和管理Component的子部件。
樹枝(Composite):定義有枝節點行爲,用來存儲子部件,在Component接口中實現與子部件有關的操作,比如增加刪除。
葉子(Leaf):在組合中表示葉節點對象,葉節點沒有子節點。
UML圖如下:
代碼如下:
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);
}
Leaf 部分:
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 Display(int depth) {
String temp = "";
for (int i = 0; i < depth; i++)
temp += '-';
System.out.println(temp + name);
}
}
Composite 部分:
private List<Component> children = new ArrayList<Component>();
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 Display(int depth) {
String temp = "";
for (int i = 0; i < depth; i++)
temp += '-';
System.out.println(temp + name);
for (Component c : children) {
c.Display(depth + 2);
}
}
}