用途
組合模式 (Component)
将對象組合成樹形結構以表示“部分-整體”的層次結構。
組合模式使得使用者對單個對象群組合對象的使用具有唯一性。
組合模式是一種結構型模式。
結構
圖-組合模式結構圖
Component : 組合中的對象聲明接口,在适當的情況下,實作所有類共有接口的預設行為。聲明一個接口用于通路和管理 Component 的子部件。
<a></a>
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);
}
Leaf : 表示葉節點對象。葉子節點沒有子節點。
class Leaf extends Component {
public Leaf(String name) {
super(name);
@Override
public void Add(Component c) {
System.out.println("Can not add to a leaf");
public void Remove(Component c) {
System.out.println("Can not remove from a leaf");
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<Component>();
public Composite(String name) {
children.add(c);
children.remove(c);
for (Component c : children) {
c.Display(depth + 2);
}
Client : 通過 Component 接口操作結構中的對象。
public class CompositePattern {
public static void main(String[] args) {
Composite root = new Composite("root");
root.Add(new Leaf("Leaf A"));
root.Add(new Leaf("Leaf B"));
Composite compX = new Composite("Composite X");
compX.Add(new Leaf("Leaf XA"));
compX.Add(new Leaf("Leaf XB"));
root.Add(compX);
Composite compXY = new Composite("Composite XY");
compXY.Add(new Leaf("Leaf XYA"));
compXY.Add(new Leaf("Leaf XYB"));
compX.Add(compXY);
root.Display(1);
應用場景
1、想要表示對象的部分-整體層次結構。
2、想要用戶端忽略組合對象與單個對象的差異,用戶端将統一地使用組合結構中的所有對象。
關于分級資料結構的一個普遍性的例子是你每次使用電腦時所遇到的:檔案系統。
檔案系統由目錄和檔案組成。每個目錄都可以裝内容。目錄的内容可以是檔案,也 可以是目錄。
按照這種方式,計算機的檔案系統就是以遞歸結構來組織的。如果你想要描述這樣的資料結構,那麼你可以使用組合模式。
要點
組合模式定義由 Leaf 對象和 Composite 對象組成的類結構;
它使得用戶端變得簡單;
它使得添加或删除子部件變得很容易。
本文轉自靜默虛空部落格園部落格,原文連結:http://www.cnblogs.com/jingmoxukong/p/4221087.html,如需轉載請自行聯系原作者