Last active
May 19, 2017 01:24
-
-
Save SoarLin/fa483d96f21735491bd55f52a79b3a6a to your computer and use it in GitHub Desktop.
Decorator 實作範例 1
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
function Sale(price) { | |
this.price = price || 100; | |
} | |
Sale.prototype.getPrice = function() { | |
return this.price; | |
}; | |
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; | |
}; | |
Sale.decorators = {}; | |
Sale.decorators.fedtax = { | |
getPrice: function() { | |
var price = this.uber.getPrice(); | |
price += price * 0.05; | |
return price; | |
} | |
}; | |
Sale.decorators.quebec = { | |
getPrice: function() { | |
var price = this.uber.getPrice(); | |
price += price * 0.075; | |
return price; | |
} | |
}; | |
Sale.decorators.money = { | |
getPrice: function() { | |
return '$' + this.uber.getPrice().toFixed(2); | |
} | |
}; | |
Sale.decorators.cdn = { | |
getPrice: function() { | |
return 'CDN$' + this.uber.getPrice().toFixed(2); | |
} | |
}; | |
var sale = new Sale(100); | |
sale = sale.decorate('fedtax'); | |
sale = sale.decorate('quebec'); | |
sale = 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