組合模式 (Component)
用途
將對象組合成樹形結構以表示“部分-整體”的層次結構。
組合模式使得用戶對單個對象和組合對象的使用具有唯一性。
組合模式是一種結構型模式。
結構
Component : 組合中的對象聲明接口,在適當的情況下,實現所有類共有接口的默認行爲。聲明一個接口用於訪問和管理 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);
}
Leaf : 表示葉節點對象。葉子節點沒有子節點。
class Leaf extends Component{
public Leaf(String name){
super(name);
}
@Override
public void add(Component component) {
System.out.println("can not add to leaf");
}
@Override
public void remove(Component component) {
System.out.println("can not remove from leaf");
}
@Override
public void display(int depth) {
String temp = "";
for(int i = 0;i < depth;i++){
temp += "-";
}
System.out.println(temp + name);
}
}
Composite : 定義枝節點行爲,用來存儲子部件,在 Component 接口中實現與子部件相關的操作。例如 Add 和 Remove。
class Composite extends Component{
private List<Component> children = new ArrayList<>();
public Composite(String name){
super(name);
}
@Override
public void add(Component component) {
children.add(component);
}
@Override
public void remove(Component component) {
children.remove(component);
}
@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);
}
}
}
Client:
public class Client {
public static void main(String[] args) {
Component c1,c2,c3,c4,c5;
c1 = new Leaf("v1");
c2 = new Leaf("c2");
c3 = new Leaf("c3");
c4 = new Composite("C4");
c5 = new Composite("C5");
c4.add(c1);
c4.add(c2);
c4.add(c3);
c5.add(c4);
//c1.display(3);
//c4.display(5);
c5.display(6);
}
}
應用場景
1、想要表示對象的部分-整體層次結構。
2、想要客戶端忽略組合對象與單個對象的差異,客戶端將統一地使用組合結構中的所有對象。
關於分級數據結構的一個普遍性的例子是你每次使用電腦時所遇到的:文件系統。
文件系統由目錄和文件組成。每個目錄都可以裝內容。目錄的內容可以是文件,也 可以是目錄。
按照這種方式,計算機的文件系統就是以遞歸結構來組織的。如果你想要描述這樣的數據結構,那麼你可以使用組合模式。
要點
組合模式定義由 Leaf 對象和 Composite 對象組成的類結構;
它使得客戶端變得簡單;
它使得添加或刪除子部件變得很容易。