设计模式
1function Sale(price) {
2 this.price = price;
3 this.decorators_list = [];
4 }
5 Sale.decorators = {};
6 Sale.decorators.fedtax = {
7 getPrice: function (price) {
8 return price + price * 5 / 100;
9 }
10 };
11 Sale.decorators.quebec = {
12 getPrice: function (price) {
13 return "$" + price.toFixed(2);
14 }
15 };
16 Sale.decorators.money = {
17 getPrice: function (price) {
18 return price + price * 7.5 / 100;
19 }
20 };
21 Sale.prototype.decorate = function (decorator) {
22 this.decorators_list.push(decorator);
23 };
24 Sale.prototype.getPrice = function () {
25 var price = this.price,
26 i,
27 max = this.decorators_list.length,
28 name;
29 for (i = 0; i < max; i++) {
30 name = this.decorators_list[i];
31 price = Sale.decorators[name].getPrice(price);
32 }
33 return price;
34 };
35 var sale = new Sale(100); sale.decorate('fedtax'); sale.decorate('money'); sale.decorate('quebec'); console.log(sale.getPrice()); //$112.88

浙公网安备 33010602011771号