java设计模式 组合_JAVA 设计模式 组合模式
用途組合模式 (Component)
將對(duì)象組合成樹形結(jié)構(gòu)以表示“部分-整體”的層次結(jié)構(gòu)。
組合模式使得用戶對(duì)單個(gè)對(duì)象和組合對(duì)象的使用具有唯一性。
組合模式是一種結(jié)構(gòu)型模式。
結(jié)構(gòu)
圖-組合模式結(jié)構(gòu)圖
Component: 組合中的對(duì)象聲明接口,在適當(dāng)?shù)那闆r下,實(shí)現(xiàn)所有類共有接口的默認(rèn)行為。聲明一個(gè)接口用于訪問和管理 Component 的子部件。
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: 表示葉節(jié)點(diǎn)對(duì)象。葉子節(jié)點(diǎn)沒有子節(jié)點(diǎn)。
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");
}
@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?
temp?+=?'-';
System.out.println(temp?+?name);
}
}
Composite: 定義枝節(jié)點(diǎn)行為,用來存儲(chǔ)子部件,在 Component 接口中實(shí)現(xiàn)與子部件相關(guān)的操作。例如 Add 和 Remove。
class?Composite?extends?Component?{
private?List?children?=?new?ArrayList();
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?
temp?+=?'-';
System.out.println(temp?+?name);
for?(Component?c?:?children)?{
c.Display(depth?+?2);
}
}
}
Client: 通過 Component 接口操作結(jié)構(gòu)中的對(duì)象。
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);
}
}
應(yīng)用場(chǎng)景
1、想要表示對(duì)象的部分-整體層次結(jié)構(gòu)。
2、想要客戶端忽略組合對(duì)象與單個(gè)對(duì)象的差異,客戶端將統(tǒng)一地使用組合結(jié)構(gòu)中的所有對(duì)象。
關(guān)于分級(jí)數(shù)據(jù)結(jié)構(gòu)的一個(gè)普遍性的例子是你每次使用電腦時(shí)所遇到的:文件系統(tǒng)。
文件系統(tǒng)由目錄和文件組成。每個(gè)目錄都可以裝內(nèi)容。目錄的內(nèi)容可以是文件,也 可以是目錄。
按照這種方式,計(jì)算機(jī)的文件系統(tǒng)就是以遞歸結(jié)構(gòu)來組織的。如果你想要描述這樣的數(shù)據(jù)結(jié)構(gòu),那么你可以使用組合模式。
要點(diǎn)
組合模式定義由 Leaf 對(duì)象和 Composite 對(duì)象組成的類結(jié)構(gòu);
它使得客戶端變得簡(jiǎn)單;
它使得添加或刪除子部件變得很容易。
推薦
參考資料
《大話設(shè)計(jì)模式》
《HeadFirst設(shè)計(jì)模式》
總結(jié)
以上是生活随笔為你收集整理的java设计模式 组合_JAVA 设计模式 组合模式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VS2017 安装xamarin 开发安
- 下一篇: [翻译]asp.net ajax xml