組合模式(Composite)把對象組合成樹形結構,以此表示「部分—整體」的層次關係。它最大的價值是讓客戶端在面對單個對象和組合對象時,使用方式完全一致,不必到處寫 if 去判斷當前節點有沒有子節點。
ASP.NET 的控件體系就是典型:一個 Control 裡可以包含子 Control,添加、刪除、遞歸遍歷的操作對父容器和葉子節點是同一套 API。DOM 也是同理,任何一個節點都可能有子節點,而 appendChild、removeChild、childNodes 對文本節點和元素節點一視同仁。
所以組合模式的關鍵是:必須有一個抽象基類,它既能代表葉子,也能代表容器。
一家餐廳的菜單結構天然是樹形的:早餐、午餐、晚餐是頂層分類,每個分類下有若干菜品,而某個菜品(比如咖啡)又可以有糖、奶這樣的附加項。需求是無論菜單還是單個菜品,都要能打印、能添加子項。
var MenuComponent = function () {};
// 信息查詢類方法
MenuComponent.prototype.getName = function () {
throw new Error("該方法必須重寫!");
};
MenuComponent.prototype.getDescription = function () {
throw new Error("該方法必須重寫!");
};
MenuComponent.prototype.getPrice = function () {
throw new Error("該方法必須重寫!");
};
MenuComponent.prototype.isVegetarian = function () {
throw new Error("該方法必須重寫!");
};
// 通用操作方法
MenuComponent.prototype.print = function () {
throw new Error("該方法必須重寫!");
};
MenuComponent.prototype.add = function () {
throw new Error("該方法必須重寫!");
};
MenuComponent.prototype.remove = function () {
throw new Error("該方法必須重寫!");
};
MenuComponent.prototype.getChild = function () {
throw new Error("該方法必須重寫!");
};
把兩類方法都放在同一個抽象上,是為了讓客戶端可以一律通過 MenuComponent 類型的引用去操作,不必關心拿到的是葉子還是枝幹。
var MenuItem = function (sName, sDescription, bVegetarian, nPrice) {
MenuComponent.apply(this);
this.sName = sName;
this.sDescription = sDescription;
this.bVegetarian = bVegetarian;
this.nPrice = nPrice;
};
MenuItem.prototype = new MenuComponent();
MenuItem.prototype.getName = function () {
return this.sName;
};
MenuItem.prototype.getDescription = function () {
return this.sDescription;
};
MenuItem.prototype.getPrice = function () {
return this.nPrice;
};
MenuItem.prototype.isVegetarian = function () {
return this.bVegetarian;
};
MenuItem.prototype.print = function () {
console.log(this.getName() + ": " + this.getDescription()
+ ", " + this.getPrice() + " euros");
};
葉子只覆寫信息查詢方法和 print,add、remove、getChild 保持繼承而來的拋錯狀態。這裡有兩種設計取向:一是像本例這樣讓調用直接拋錯,二是改成空實現靜默忽略。前者更容易暴露問題,後者對客戶端更寬容,取決於團隊偏好。
var Menu = function (sName, sDescription) {
MenuComponent.apply(this);
this.aMenuComponents = [];
this.sName = sName;
this.sDescription = sDescription;
};
Menu.prototype = new MenuComponent();
Menu.prototype.add = function (oMenuComponent) {
this.aMenuComponents.push(oMenuComponent);
};
Menu.prototype.remove = function (oMenuComponent) {
var aMenuItems = [];
var nMenuItem = 0;
var nLenMenuItems = this.aMenuComponents.length;
var oItem = null;
for (; nMenuItem < nLenMenuItems;) {
oItem = this.aMenuComponents[nMenuItem];
if (oItem !== oMenuComponent) {
aMenuItems.push(oItem);
}
nMenuItem = nMenuItem + 1;
}
this.aMenuComponents = aMenuItems;
};
Menu.prototype.getChild = function (nIndex) {
return this.aMenuComponents[nIndex];
};
Menu.prototype.getName = function () {
return this.sName;
};
Menu.prototype.getDescription = function () {
return this.sDescription;
};
// 關鍵:先打印自己,再遞歸打印所有子節點
Menu.prototype.print = function () {
console.log(this.getName() + ": " + this.getDescription());
console.log("--------------------------------------------");
var nMenuComponent = 0;
var nLenMenuComponents = this.aMenuComponents.length;
var oMenuComponent = null;
for (; nMenuComponent < nLenMenuComponents;) {
oMenuComponent = this.aMenuComponents[nMenuComponent];
oMenuComponent.print();
nMenuComponent = nMenuComponent + 1;
}
};
print 裡沒有任何類型判斷,只是對每個子節點呼叫 print()。子節點是 MenuItem 就打印一行,是 Menu 就繼續遞歸下去——這正是組合模式「一致性」的體現。
var DinnerMenu = function () {
Menu.apply(this);
};
DinnerMenu.prototype = new Menu();
var CafeMenu = function () {
Menu.apply(this);
};
CafeMenu.prototype = new Menu();
var PancakeHouseMenu = function () {
Menu.apply(this);
};
PancakeHouseMenu.prototype = new Menu();
var Mattress = function (aMenus) {
this.aMenus = aMenus;
};
Mattress.prototype.printMenu = function () {
this.aMenus.print();
};
它只負責接收一個菜單作為入口,然後把打印請求轉發下去。
var oPanCakeHouseMenu = new Menu("Pancake House Menu", "Breakfast");
var oDinnerMenu = new Menu("Dinner Menu", "Lunch");
var oCoffeeMenu = new Menu("Cafe Menu", "Dinner");
var oAllMenus = new Menu("ALL MENUS", "All menus combined");
oAllMenus.add(oPanCakeHouseMenu);
oAllMenus.add(oDinnerMenu);
oDinnerMenu.add(new MenuComponent
? new MenuItem("Pasta", "Spaghetti with Marinara Sauce, and a slice of sourdough bread", true, 3.89)
: null);
oDinnerMenu.add(oCoffeeMenu);
oCoffeeMenu.add(new MenuItem("Express", "Coffee from machine", false, 0.99));
var oMattress = new Mattress(oAllMenus);
console.log("---------------------------------------------");
oMattress.printMenu();
console.log("---------------------------------------------");
一句 oMattress.printMenu(),就把整棵樹、任意層深、任意數量分支的內容全部打印出來。新增一個「素食菜單」分類,客戶端代碼一行都不用改。
組合模式的使用時機同樣清晰:
另外要注意它常與裝飾者模式搭配使用:兩者通常共享一個公共父類(原型),因此裝飾器必須支持具有 add、remove、getChild 操作的 Component 接口。理解這一點,就能明白為什麼 Java I/O 裡的 InputStream 系列既能嵌套又能包裝。