Advertisement
Advanced Java, Design Patterns in Java

How would you implement the Decorator pattern in Java, and how does java.io's InputStream/OutputStream class hierarchy exemplify this pattern in the JDK itself?

Short answer

Decorator lets you dynamically add responsibilities to an object by wrapping it in one or more decorator objects that implement the same interface as the original, each adding its own behavior before/after delegating to the wrapped object -- java.io is the JDK's own canonical…

Save Java mock interview
Advertisement
AModel answer
Decorator lets you dynamically add responsibilities to an object by wrapping it in one or more decorator objects that implement the same interface as the original, each adding its own behavior before/after delegating to the wrapped object -- java.io is the JDK's own canonical real-world example: FileInputStream provides raw byte reading, and it can be wrapped in a BufferedInputStream (adds buffering) which can itself be wrapped in a GZIPInputStream (adds decompression), each layer transparently adding behavior while preserving the common InputStream interface, letting you compose exactly the combination of behaviors you need without an explosion of subclasses covering every possible combination.
InputStream raw = new FileInputStream("data.gz");
InputStream buffered = new BufferedInputStream(raw);      // adds buffering
InputStream decompressed = new GZIPInputStream(buffered);  // adds decompression

// Each layer implements InputStream and delegates to the wrapped stream,
// composing behaviors without needing a single "BufferedGZIPFileInputStream" class
Real-world example
A custom logging framework wraps a base Logger implementation in decorator layers adding timestamp formatting, then request-correlation-ID injection, then asynchronous batching, letting each concern be independently composed and tested rather than requiring one monolithic class handling all these responsibilities together.
Likely follow-ups
  • Why does this pattern avoid the 'class explosion' problem that inheritance-based combination of behaviors would create?
  • How does Decorator differ structurally from the Proxy pattern, given both wrap an object behind the same interface?
Related topics