Junior — Middle
Explain the concept of the Decorator pattern and its advantage in the design of software systems.
sobes.tech AI
Answer from AI
The Decorator pattern allows dynamically adding new responsibilities to objects by wrapping them in other decorator objects that implement the same interface. This is an alternative to inheritance for extending functionality.
Advantages:
- Flexibility: decorators can be combined in various orders and quantities.
- Avoids exponential class growth through inheritance.
- Allows adding behavior at runtime.
Example in JavaScript (Node.js):
class Coffee {
cost() { return 5; }
}
class MilkDecorator {
constructor(coffee) { this.coffee = coffee; }
cost() { return this.coffee.cost() + 2; }
}
const simpleCoffee = new Coffee();
const milkCoffee = new MilkDecorator(simpleCoffee);
console.log(milkCoffee.cost()); // 7
Here, MilkDecorator adds the cost of milk to the base coffee.