```
//javascript 裝飾者模式
//
function Sale(price) {
this.price = price || "100";
this.decorates_list = [];//要裝飾的
}
Sale.prototype.getPrice = function () {
var price = this.price,
i,
name,
max = this.decorates_list.length;
for (i = 0; i < max; i++) {
name = this.decorates_list[i];
price = Sale.decorators[name].getPrice(price);
}
return price;
}
//裝飾方法
//@parames decorator 裝飾物名字
Sale.prototype.decorate = function (decorator) {
this.decorates_list.push(decorator);
}
Sale.decorators={};//裝飾物集合
//裝飾物罕袋,商品包郵
Sale.decorators.baoyou={
getPrice: function(price){
return price - 10;
}
}
//裝飾物秩霍,商品打折
Sale.decorators.dazhe={
getPrice: function(price){
return price * 0.8;
}
}
//測試
var s = new Sale(99);
s.decorate("baoyou");
s.decorate("dazhe");
console.log(s.getPrice());
```