Created
January 3, 2012 20:36
-
-
Save ValeriiVasin/1556806 to your computer and use it in GitHub Desktop.
[javascript patterns] Decorator.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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