Skip to main content
PreparationZone Logo
PreparationZone
Back to Java

Java · Easy · Free

Decorator pattern — InputStream wrappers example?

JavaDesign PatternsFresher
Model answer

Decorator pattern

Decorator wraps an object to add behavior while preserving the same interface. Java I/O is the textbook case: InputStream decorators add buffering, decompression, or charset decoding without subclassing every combination.

  • new BufferedInputStream(new FileInputStream(path)) — fewer syscalls.
  • GZIPInputStream — transforms bytes on read; still an InputStream.
  • Decorators are transparent to callers that only need the base type.
  • Order matters: buffer around gzip vs gzip around buffer changes performance.
java
try (InputStream in = new BufferedInputStream(
        new GZIPInputStream(new FileInputStream("data.gz")))) {
    byte[] buf = in.readNBytes(4096);
}
Link to try-with-resources: outer decorator closes the whole chain when the outermost wrapper is closed.