Decorador
Concepto del Patrón Decorador
Ejemplo en TypeScript
// Componente base
interface Coffee {
getCost(): number;
getDescription(): string;
}
// Clase concreta base
class SimpleCoffee implements Coffee {
getCost(): number {
return 10;
}
getDescription(): string {
return "Simple coffee";
}
}
// Decorador base
abstract class CoffeeDecorator implements Coffee {
protected decoratedCoffee: Coffee;
constructor(coffee: Coffee) {
this.decoratedCoffee = coffee;
}
getCost(): number {
return this.decoratedCoffee.getCost();
}
getDescription(): string {
return this.decoratedCoffee.getDescription();
}
}
// Decorador concreto: Milk
class WithMilk extends CoffeeDecorator {
constructor(coffee: Coffee) {
super(coffee);
}
getCost(): number {
return this.decoratedCoffee.getCost() + 2;
}
getDescription(): string {
return this.decoratedCoffee.getDescription() + ", with milk";
}
}
// Decorador concreto: Sugar
class WithSugar extends CoffeeDecorator {
constructor(coffee: Coffee) {
super(coffee);
}
getCost(): number {
return this.decoratedCoffee.getCost() + 1;
}
getDescription(): string {
return this.decoratedCoffee.getDescription() + ", with sugar";
}
}
// Uso del decorador
const simpleCoffee = new SimpleCoffee();
console.log(simpleCoffee.getDescription() + " costs $" + simpleCoffee.getCost());
const milkCoffee = new WithMilk(simpleCoffee);
console.log(milkCoffee.getDescription() + " costs $" + milkCoffee.getCost());
const sugarMilkCoffee = new WithSugar(milkCoffee);
console.log(sugarMilkCoffee.getDescription() + " costs $" + sugarMilkCoffee.getCost());Explicación
Last updated