☕ Java Advanced

What is the Decorator design pattern in Java?

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.