Skip to content

Instantly share code, notes, and snippets.

@ValeriiVasin
Created January 3, 2012 20:36
Show Gist options
  • Save ValeriiVasin/1556806 to your computer and use it in GitHub Desktop.
Save ValeriiVasin/1556806 to your computer and use it in GitHub Desktop.
[javascript patterns] Decorator.
var Sale = function (price) {
this.price = price > 0 ? price : 100;
this.decorators_list = [];
};
Sale.decorators = {};
Sale.decorators.fedtax = {
getPrice: function (price) {
return price + price * 0.05;
}
};
Sale.decorators.quebec = {
getPrice: function (price) {
return price + price * 0.075;
}
};
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;
};
// usage
var iPhone = new Sale(100);
iPhone.decorate('quebec');
iPhone.decorate('fedtax');
iPhone.decorate('money');
console.log(iPhone.getPrice());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment