深入理解JavaScript系列(40):設計模式之組合模式詳解
介紹
組合模式(Composite)將對象組合成樹形結構以表示“部分-整體”的層次結構,組合模式使得用戶對單個對象和組合對象的使用具有一致性。
常見的場景有asp.net里的控件機制(即control里可以包含子control,可以遞歸操作、添加、刪除子control),類似的還有DOM的機制,一個DOM節(jié)點可以包含子節(jié)點,不管是父節(jié)點還是子節(jié)點都有添加、刪除、遍歷子節(jié)點的通用功能。所以說組合模式的關鍵是要有一個抽象類,它既可以表示子元素,又可以表示父元素。
正文
舉個例子,有家餐廳提供了各種各樣的菜品,每個餐桌都有一本菜單,菜單上列出了該餐廳所偶的菜品,有早餐糕點、午餐、晚餐等等,每個餐都有各種各樣的菜單項,假設不管是菜單項還是整個菜單都應該是可以打印的,而且可以添加子項,比如午餐可以添加新菜品,而菜單項咖啡也可以添加糖啊什么的。
這種情況,我們就可以利用組合的方式將這些內容表示為層次結構了。我們來逐一分解一下我們的實現(xiàn)步驟。
第一步,先實現(xiàn)我們的“抽象類”函數(shù)MenuComponent:
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("該方法必須重寫!");
};
該函數(shù)提供了2種類型的方法,一種是獲取信息的,比如價格,名稱等,另外一種是通用操作方法,比如打印、添加、刪除、獲取子菜單。
第二步,創(chuàng)建基本的菜品項:
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");
};
由代碼可以看出,我們只重新了原型的4個獲取信息的方法和print方法,沒有重載其它3個操作方法,因為基本菜品不包含添加、刪除、獲取子菜品的方式。
第三步,創(chuàng)建菜品:
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;
}
};
注意上述代碼,除了實現(xiàn)了添加、刪除、獲取方法外,打印print方法是首先打印當前菜品信息,然后循環(huán)遍歷打印所有子菜品信息。
第四步,創(chuàng)建指定的菜品:
我們可以創(chuàng)建幾個真實的菜品,比如晚餐、咖啡、糕點等等,其都是用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();
第五步,創(chuàng)建最頂級的菜單容器——菜單本:
var Mattress = function (aMenus) {
this.aMenus = aMenus;
};
Mattress.prototype.printMenu = function () {
this.aMenus.print();
};
該函數(shù)接收一個菜單數(shù)組作為參數(shù),并且值提供了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控件開發(fā)的同學,是不是看起來很熟悉?
總結
組合模式的使用場景非常明確:
你想表示對象的部分-整體層次結構時;
你希望用戶忽略組合對象和單個對象的不同,用戶將統(tǒng)一地使用組合結構中的所有對象(方法)
另外該模式經常和裝飾者一起使用,它們通常有一個公共的父類(也就是原型),因此裝飾必須支持具有add、remove、getChild操作的 component接口。
相關文章
深入理解JavaScript系列(18):面向對象編程之ECMAScript實現(xiàn)
這篇文章主要介紹了深入理解JavaScript系列(18):面向對象編程之ECMAScript實現(xiàn),本文講解了數(shù)據(jù)類型、原始值類型、Object類型、動態(tài)性、內置對象、原生對象及宿主對象等內容,需要的朋友可以參考下2015-03-03js數(shù)組直接賦值的問題(js數(shù)組的淺拷貝與深拷貝方法)
JS數(shù)組在直接賦值時屬于數(shù)組的淺拷貝,新數(shù)組保存的是原數(shù)據(jù)的內存地址,修改新數(shù)組或原數(shù)組其中一個數(shù)組,另一個數(shù)組也會相應的變化,數(shù)組的直接賦值屬于數(shù)組的淺拷貝,JS存儲對象都是存內存地址2022-10-10關于JavaScript的變量的數(shù)據(jù)類型的判斷方法
這篇文章主要介紹了關于JavaScript的變量的數(shù)據(jù)類型的判斷方法,JS是一種弱類型語言,其數(shù)據(jù)類型的相關特性有時也受到不少開發(fā)者的詬病,需要的朋友可以參考下2015-08-08js實現(xiàn)unicode碼字符串與utf8字節(jié)數(shù)據(jù)互轉詳解
這篇文章主要介紹了js實現(xiàn)unicode碼字符串與utf8字節(jié)數(shù)據(jù)互轉,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-03-03jquery應該如何來設置改變按鈕input的onclick事件
要動態(tài)改變這個上一頁按鈕中onclick的函數(shù).我自己是嘗試了很多種方法,都沒有做出來,下面列舉的幾個都是失敗的例子,需要的朋友可以參考下2012-12-12