function Sale(price){ this.price = price || 100; this.decorators_list = [];// 装饰着列表作为自身的属性 } // 追加列表 Sale.prototype.decorate = function(decorator){ this.decorators_list.push(decorator); }; // getPrice 完成所有工作 Sale.prototype.getPrice = function(){ var price = this.price, i, max = this.decorators_list.length, name; console.log("初始price:", price, "有几个装饰者:", max);// 100 3 for(i = 0; i < max; i++){ console.log("每次单独的初始price:", price);// 100 105 112.875 name = this.decorators_list[i]; console.log("names are as follows::", name); price = Sale.decorators[name].getPrice(price); console.log("every step , this price is changing:",price) } return price; }; Sale.decorators = {};// 子类 decorators 是一个object Sale.decorators.fedtax = {// 子子类 getPrice : function(price){ return price + price * 5 / 100; } }; Sale.decorators.quebec = { getPrice : function(price){ return price + price * 7.5 / 100; } }; Sale.decorators.money = { getPrice : function(price){ return "$" + price.toFixed(2); } }; var sale = new Sale(100); sale.decorate('fedtax'); sale.decorate('quebec'); sale.decorate('money'); var a = sale.getPrice(); console.log(a);
说明:
上面是使用列表实现装饰者模式的。