深入理解JavaScript系列(40):設計模式之組合模式

來源:互聯網
上載者:User
介紹

組合模式(Composite)將對象組合成樹形結構以表示“部分-整體”的階層,組合模式使得使用者對單個對象和組合對象的使用具有一致性。

常見的情境有asp.net裡的控制項機制(即control裡可以包含子control,可以遞迴操作、添加、刪除子control),類似的還有 DOM的機制,一個DOM節點可以包含子節點,不管是父節點還是子節點都有添加、刪除、遍曆子節點的通用功能。所以說組合模式的關鍵是要有一個抽象類別,它 既可以表示子項目,又可以表示父元素。

本文

舉個例子,有家餐廳提供了各種各樣的菜品,每個餐桌都有一本菜單,菜單上列出了該餐廳所偶的菜品,有早餐糕點、午餐、晚餐等等,每個餐都有各種各樣 的功能表項目,假設不管是功能表項目還是整個菜單都應該是可以列印的,而且可以添加子項,比如午餐可以添加新菜品,而功能表項目咖啡也可以添加糖啊什麼的。

這種情況,我們就可以利用組合的方式將這些內容表示為階層了。我們來逐一分解一下我們的實現步驟。

第一步,先實現我們的“抽象類別”函數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("該方法必須重寫!");
};

該函數提供了2種類型的方法,一種是擷取資訊的,比如價格,名稱等,另外一種是通用操作方法,比如列印、添加、刪除、擷取子功能表。

第二步,建立基本的菜品項:

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個操作方法,因為基本菜品不包含添加、刪除、擷取子菜品的方式。

第三步,建立菜品:

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;
}
};

注意上述代碼,除了實現了添加、刪除、擷取方法外,列印print方法是首先列印當前菜品資訊,然後迴圈遍曆列印所有子菜品資訊。

第四步,建立指定的菜品:

我們可以建立幾個真實的菜品,比如晚餐、咖啡、糕點等等,其都是用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控制項開發的同學,是不是看起來很熟悉?

總結

組合模式的使用情境非常明確:

  1. 你想表示對象的部分-整體階層時;
  2. 你希望使用者忽略組合對象和單個對象的不同,使用者將統一地使用組合結構中的所有對象(方法)

另外該模式經常和裝飾者一起使用,它們通常有一個公用的父類(也就是原型),因此裝飾必須支援具有add、remove、getChild操作的 component介面。

參考:https://github.com/tcorral/Design-Patterns-in-Javascript/blob/master/Composite/index.html

轉自:湯姆大叔

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.