Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save frontdevops/3f3ca9312714470367c1 to your computer and use it in GitHub Desktop.
Save frontdevops/3f3ca9312714470367c1 to your computer and use it in GitHub Desktop.
/**
* 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