What are the advantages of using the Decorator pattern for extending behavior?

The Decorator pattern's main advantage for extending behavior is that it adds functionality dynamically, at runtime, through composition rather than static inheritance. This makes it far more flexible than baking every behavior combination into the class hierarchy.

Key Points: • Behavior can be added or removed at runtime by wrapping or unwrapping decorators, unlike inheritance which is fixed at compile time. • Decorators can be stacked in any combination, letting you compose behaviors instead of hardcoding every variant as its own subclass. • It avoids the combinatorial subclass explosion you'd get trying to represent every feature combination through inheritance. • Each decorator has a single, focused responsibility, which keeps individual classes small and easy to test. • The original class stays untouched, so existing code that depends on it is unaffected by new decorators.

Example: Instead of creating classes for every combination of coffee add-ons (MilkCoffee, SugarCoffee, MilkSugarCoffee, ...), you wrap a base Coffee object with independent MilkDecorator and SugarDecorator instances as needed.

Interview Tip: A concise interview answer is:

"Decorator lets you add behavior at runtime through composition instead of baking every combination into a rigid class hierarchy, so you avoid a subclass explosion when there are several optional features. Each decorator stays focused on one responsibility, and you can stack them in whatever combination the situation calls for without touching the original class."