添加子菜品
this.aMenuComponents.push(oMenuComponent);
};
Menu.prototype.remove = function (oMenuComponent) {
//
删除子菜品
var aMenuItems = [];
var nMenuItem = 0;
var nLenMenuItems = this.aMenuComponents.length;
var oItem = null;
@H_
301_0@ 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("--------------------------------------------");
@H_
301_0@ var nMenuComponent = 0;
var nLenMenuComponents = this.aMenuComponents.length;
var oMenuComponent = null;
@H_
301_0@ for (; nMenuComponent < nLenMenuComponents; ) {
oMenuComponent = this.aMenuComponents[nMenuComponent];
oMenuComponent.print();
nMenuComponent = nMenuComponent + 1;
}
};
@H_
301_0@var CafeMenu = function () {
Menu.apply(this);
};
CafeMenu.prototype = new Menu();
@H_
301_0@var PancakeHouseMenu = function () {
Menu.apply(this);
};
PancakeHouseMenu.prototype = new Menu();
该
函数接收一个
菜单数组作为参数,并且值提供了printMenu
方法用于打印所有的
菜单内容。
@H_
301_0@第六步,
调用方式:
@H_
301_0@oAllMenus.add(oPanCakeHouseMenu);
oAllMenus.add(oDinnerMenu);
@H_
301_0@oDinnerMenu.add(new MenuItem("Pasta","Spaghetti with Marinara Sauce,and a slice of sourdough bread",true,3.89));
oDinnerMenu.add(oCoffeeMenu);
@H_
301_0@oCoffeeMenu.add(new MenuItem("Express","Coffee from machine",false,0.99));
@H_
301_0@var oMattress = new Mattress(oAllMenus);
console.log("---------------------------------------------");
oMattress.printMenu();
console.log("---------------------------------------------");
熟悉asp.net控件开发的同学,是不是看起来很熟悉?
@H_
301_0@
总结
@H_
301_0@组合模式的使用场景非常明确:
@H_
301_0@你想表示对象的部分-整体层次结构时;
你希望
用户忽略组合对象和单个对象的不同,
用户将统一地使用组合结构中的所有对象(
方法)
另外该模式经常和装饰者一起使用,它们通常有一个公共的
父类(也就是原型),因此装饰必须
支持具有add、remove、getChild操作的 component接口。