← All Quizzes
What is the Decorator pattern and how does it differ from inheritance?
Explanation
The Decorator pattern dynamically adds behavior to individual objects without affecting other objects of the same class. It uses composition (wrapping) rather than inheritance, allowing behavior to be added at runtime and stacked in any combination. Decorators conform to the same interface as the decorated object, making them transparent to clients. Unlike inheritance (static, one class), decorators are flexible and composable. Examples: Java I/O streams (BufferedInputStream wrapping FileInputStream), middleware in web frameworks, and Python decorators. Decorators support the Open/Closed Principle.