☕ Java Advanced

What is the Decorator design pattern in Java?

Why Interviewers Ask This

Interviewers ask this to evaluate whether you have the depth of knowledge needed to mentor others and lead technical decisions. The expected answer goes beyond definitions into practical implications and real-world consequences.

Answer

The Decorator pattern attaches additional responsibilities to an object dynamically by wrapping it in decorator objects that share the same interface. This provides a flexible alternative to subclassing for extending functionality. The decorator wraps the original component and adds behavior before or after delegating to it. Java I/O is the classic example: new BufferedInputStream(new FileInputStream(file))BufferedInputStream decorates FileInputStream with buffering. You can stack decorators: new DataInputStream(new BufferedInputStream(new FileInputStream(file))) adds type-aware reading on top of buffering. Each decorator adds one responsibility, following the Single Responsibility Principle while enabling combinatorial feature extension without class explosion.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Java codebase.