本篇解析組合模式(Composite)。它把物件組合成樹狀結構,用以表示「部分—整體」的層級關係,並讓使用者對待單一物件與組合物件的方式保持一致。
這個模式在日常開發中隨處可見。ASP.NET 的控件體系就是典型例子:一個 control 裡可以包含子 control,並支援遞迴的加入、刪除與遍歷;DOM 也是同樣的道理,任何節點都能包含子節點,而不論父節點還是子節點,都具備通用的新增、移除、走訪能力。
由此可見,組合模式的關鍵在於:必須存在一個抽象類,它既能代表子元素,也能代表父元素。這正是「一致性」的技術基礎。
想像一家餐廳提供各式菜品,每張餐桌都有一本菜單,上面列著早餐糕點、午餐、晚餐等分類;每個分類底下又有各種菜品項目。假設不論是單一菜品還是整份菜單,都應該可以被列印,而且都能往下加入子項——午餐可以新增菜色,咖啡也可以加上糖。這種結構用組合模式來表達最為自然。
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("該方法必須重寫!");
};
這個函式提供了兩類方法:一類是取得資訊的(名稱、描述、價格、是否素食),另一類是通用操作(列印、加入、移除、取得子項)。全部丟出錯誤,是為了強制子類必須自行覆寫。
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");
};
注意此處只覆寫了四個取值的 getter 與 print,並沒有實作 add、remove、getChild——因為單一菜品本身不可能再往下容納子菜品。這是組合模式中「葉節點」的典型樣貌。
var Menu = function (sName, sDescription) {
MenuComponent.apply(this);
this.aMenuComponents = [];
this.sName = sName;
this.sDescription = sDescription;
this.createIterator = function () {
throw new Error("This method must be overwritten!");
};
};
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;
}
};
除了 add、remove、getChild 之外,print 的實作是重點:它先印出本身資訊,再迴圈呼叫每個子項的 print()。由於子項可能又是 Menu,於是形成遞迴,整棵樹就被完整走訪——而呼叫端完全不需要知道節點是葉子還是分支。這就是「一致性」帶來的簡潔。
幾個真實分類都以 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();
};
它接收一組菜單,並只提供 printMenu 一個方法,用來列印全部內容。
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 MenuItem("Pasta", "Spaghetti with Marinara Sauce, and a slice of sourdough bread", true, 3.89));
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("---------------------------------------------");
有 ASP.NET 控件開發經驗的人,看到這段結構應該會感到十分熟悉。
組合模式的適用場合非常明確:
當你想表示物件的「部分—整體」層級結構時;以及當你希望使用者忽略組合物件與單一物件的差別,能統一地使用整個結構中的所有物件(方法)時。
此外,這個模式常與裝飾者模式搭配,因為它們通常共享同一個父類(也就是原型),所以裝飾器必須支援具有 add、remove、getChild 操作的 component 介面。