javascript 装饰者模式
2017-01-26 本文已影响0人
恩行我的流量
```
//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());
```