Junior — Middle
What is the purpose and application of the Decorator pattern in programming?
sobes.tech AI
Answer from AI
The Decorator pattern allows dynamically adding new responsibilities to objects by wrapping them in other decorator objects without changing the original class.
This is useful when you need to extend functionality without creating a large number of subclasses.
Example of usage in Node.js:
class Coffee {
cost() {
return 5;
}
}
class MilkDecorator {
constructor(coffee) {
this.coffee = coffee;
}
cost() {
return this.coffee.cost() + 2; // add the cost of milk
}
}
const simpleCoffee = new Coffee();
const milkCoffee = new MilkDecorator(simpleCoffee);
console.log(milkCoffee.cost()); // 7
Thus, the pattern allows flexible combination of object behaviors at runtime.