Created
January 19, 2016 20:57
-
-
Save frontdevops/3f3ca9312714470367c1 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Base decorator for Coffee ingredients | |
* @param target | |
* @param cost | |
* @returns {any} | |
*/ | |
function baseCoffeeIngredientDecorator(target, cost) { | |
// save a reference to the original constructor | |
var original = target; | |
// a utility function to generate instances of a class | |
function construct(constructor, args) { | |
const c :any = function () { | |
return constructor.apply(this, args); | |
}; | |
c.prototype = constructor.prototype; | |
let ret = new c(); | |
ret.cost += cost; | |
return ret; | |
} | |
// the new constructor behaviour | |
const f :any = function (...args) { | |
return construct(original, args); | |
}; | |
// copy prototype so intanceof operator still works | |
f.prototype = original.prototype; | |
// return new constructor (will override original) | |
return f; | |
} | |
/** | |
* Decorator A | |
*/ | |
function withMilk(target) { return baseCoffeeIngredientDecorator(target, 0.5) } | |
/** | |
* Decorator B | |
*/ | |
function withWhip(target) { return baseCoffeeIngredientDecorator(target, 0.7) } | |
/** | |
* Decorator C | |
*/ | |
function withSprinkles(target) { return baseCoffeeIngredientDecorator(target, 0.2) } | |
/** | |
* ConcreteComponent | |
* (class for decorate) | |
*/ | |
@withMilk | |
@withWhip | |
@withSprinkles | |
class Coffee { | |
private cost :number = 1; | |
getCost() :number { | |
return this.cost; | |
} | |
} | |
var myCoffee = new Coffee(); | |
console.log(myCoffee.getCost()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment