Skip to content

Instantly share code, notes, and snippets.

@Sljubura
Created March 5, 2013 19:56
Show Gist options
  • Save Sljubura/5093688 to your computer and use it in GitHub Desktop.
Save Sljubura/5093688 to your computer and use it in GitHub Desktop.
Decorator pattern
// Constructor
function Sale(price) {
this.price = price || 10
}
Sale.prototype.getPrice = function () {
return this.price;
};
Sale.decorators = {};
Sale.decorators.statetax = {
getPrice: function () {
var price = this.uber.getPrice();
price += price * 2 / 100;
return price;
}
};
Sale.decorators.incometax = {
getPrice: function () {
var price = this.uber.getPrice();
price += price * 3 / 100;
}
};
Sale.prototype.decorate = function (decorator) {
var F = function () {},
overrides = this.constructor.decorators[decorator],
i, newobj;
F.prototype = this;
newobj = new F();
newobj.uber = F.prototype;
for (i in overrides) {
if (overrides.hasOwnProperty(i)) {
newobj[i] = overrides[i];
}
}
return newobj;
};
@SergeyErmolaev
Copy link

var sale = new Sale(100);
sale.decorate('fedtax');// цена 100 долларов
sale.decorate('quebec');// добавить федеральный налог
sale.decorate('money');// форматировать как денежную сумму
sale.getPrice();// “$112.88”
Не работает, $112,88 не получится

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment