Skip to content

Instantly share code, notes, and snippets.

@SoarLin
Created May 19, 2017 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SoarLin/197032e9146b10a8101361acfb219596 to your computer and use it in GitHub Desktop.
Save SoarLin/197032e9146b10a8101361acfb219596 to your computer and use it in GitHub Desktop.
Decorator 實作範例 2
function Sale(price) {
this.price = price || 100;
this.decorators_list = [];
}
Sale.decorators = {};
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);
}
};
Sale.prototype.decorate = function (decorator) {
this.decorators_list.push(decorator);
};
Sale.prototype.getPrice = function() {
var price = this.price,
i,
max = this.decorators_list.length,
name;
for (i = 0; i < max; i+= 1) {
name = this.decorators_list[i];
price = Sale.decorators[name].getPrice(price);
}
return price;
};
var sale = new Sale(100);
sale.decorate('fedtax');
sale.decorate('quebec');
sale.decorate('money');
console.log(sale.getPrice());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment