Video in progress
Explain the Decorator pattern using Java I/O classes as the example.
A Decorator wraps an object in another object with the same interface and adds new behavior to it. In Java I/O, BufferedInputStream(new FileInputStream(...)) is exactly that: each layer adds one capability.
📖 Answer
try (InputStream in = new GZIPInputStream(
new BufferedInputStream(
new FileInputStream("logs.gz")))) {
// reads from the file -> buffers -> decompresses
}
All three classes are InputStreams. Each one holds the stream inside it and does read() in its own way. That's why you can stack them in any order and in any number.
If this had been done with inheritance, you'd have BufferedGzipFileInputStream, BufferedFileInputStream, GzipFileInputStream... and the number of combinations would explode. Decorator solves it with composition.
Sign up to mark studied questions and save your progress.