Design Patterns (GoF) (50 Qs)•Part 1: Creational & Structural Patterns (1 - 10)
What is the Decorator Pattern and how does it differ from Inheritance?
junior LevelCode ExampleTypeScript
In Simple Words: Attaches new behaviors to objects dynamically at runtime by placing them inside special wrapper objects:
- Inheritance: Static (compile-time) and causes class explosion (e.g.
EspressoWithMilk,EspressoWithMilkAndCaramel). - Decorator: You wrap a base object with multiple decorators dynamically:
typescript
let coffee: Beverage = new Espresso();
coffee = new MilkDecorator(coffee);
coffee = new CaramelDecorator(coffee);
console.log(coffee.cost()); // Dynamically sums cost!