介紹
組合模式(Composite)將對(duì)象組合成樹(shù)形結(jié)構(gòu)以表示“部分-整體”的層次結(jié)構(gòu),組合模式使得用戶對(duì)單個(gè)對(duì)象和組合對(duì)象的使用具有一致性。
常見(jiàn)的場(chǎng)景有asp.net里的控件機(jī)制(即control里可以包含子control,可以遞歸操作、添加、刪除子control),類似的還有DOM的機(jī)制,一個(gè)DOM節(jié)點(diǎn)可以包含子節(jié)點(diǎn),不管是父節(jié)點(diǎn)還是子節(jié)點(diǎn)都有添加、刪除、遍歷子節(jié)點(diǎn)的通用功能。所以說(shuō)組合模式的關(guān)鍵是要有一個(gè)抽象類,它既可以表示子元素,又可以表示父元素。
正文
舉個(gè)例子,有家餐廳提供了各種各樣的菜品,每個(gè)餐桌都有一本菜單,菜單上列出了該餐廳所偶的菜品,有早餐糕點(diǎn)、午餐、晚餐等等,每個(gè)餐都有各種各樣的菜單項(xiàng),假設(shè)不管是菜單項(xiàng)還是整個(gè)菜單都應(yīng)該是可以打印的,而且可以添加子項(xiàng),比如午餐可以添加新菜品,而菜單項(xiàng)咖啡也可以添加糖啊什么的。
這種情況,我們就可以利用組合的方式將這些內(nèi)容表示為層次結(jié)構(gòu)了。我們來(lái)逐一分解一下我們的實(shí)現(xiàn)步驟。
第一步,先實(shí)現(xiàn)我們的“抽象類”函數(shù)MenuComponent:
第二步,創(chuàng)建基本的菜品項(xiàng):
由代碼可以看出,我們只重新了原型的4個(gè)獲取信息的方法和print方法,沒(méi)有重載其它3個(gè)操作方法,因?yàn)榛静似凡话砑印h除、獲取子菜品的方式。
第三步,創(chuàng)建菜品:
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 () {
// 打印當(dāng)前菜品以及所有的子菜品
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;
}
};
第四步,創(chuàng)建指定的菜品:
我們可以創(chuàng)建幾個(gè)真實(shí)的菜品,比如晚餐、咖啡、糕點(diǎn)等等,其都是用Menu作為其原型,代碼如下:
var CafeMenu = function () {
Menu.apply(this);
};
CafeMenu.prototype = new Menu();
var PancakeHouseMenu = function () {
Menu.apply(this);
};
PancakeHouseMenu.prototype = new Menu();
第六步,調(diào)用方式:
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("---------------------------------------------");
總結(jié)
組合模式的使用場(chǎng)景非常明確:
你想表示對(duì)象的部分-整體層次結(jié)構(gòu)時(shí);
你希望用戶忽略組合對(duì)象和單個(gè)對(duì)象的不同,用戶將統(tǒng)一地使用組合結(jié)構(gòu)中的所有對(duì)象(方法)
另外該模式經(jīng)常和裝飾者一起使用,它們通常有一個(gè)公共的父類(也就是原型),因此裝飾必須支持具有add、remove、getChild操作的 component接口。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注