CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 4 of 6 · 2 min read

In Java

Streams and a logging wrapper.

Java's I/O library is built this way. A BufferedReader wraps an InputStreamReader, which wraps an input stream. Each layer adds one thing: converting bytes to characters, then buffering lines.

BufferedReader br = new BufferedReader(
    new InputStreamReader(new ByteArrayInputStream("line one\nline two\n".getBytes())));
System.out.println(br.readLine());   // line one

HF uses this as its real-world example, and also notes a downside: code that checks for a specific concrete type breaks when a decorator wraps it, because the wrapper is not that type.

Another common use is a cross-cutting concern, behaviour that applies to many classes, such as logging, caching, retries or timing. A decorator adds it without editing the wrapped class, which keeps the single responsibility principle (Level 2, module 1).

interface Repo { void save(String id); }

class LoggingRepo implements Repo {
    private final Repo inner;
    private final List<String> log;
    LoggingRepo(Repo r, List<String> log) { inner = r; this.log = log; }

    public void save(String id) {
        log.add("saving " + id);
        inner.save(id);
        log.add("saved " + id);
    }
}

Saving "b1" through the wrapper leaves the log [saving b1, saved b1] and the inner store [b1]. The real repository knows nothing about logging, and it can be wrapped again in a retry decorator or a cache.

EJ makes a related point in Item 18, where it advises composition and forwarding over inheritance. Its wrapper class holds an instance of the wrapped type and forwards each call, adding behaviour on the way. EJ names this the Decorator pattern. Its example shows that a wrapper stays correct even if the wrapped class changes its inner workings, while a subclass can break.

Check yourself: 1. What does LoggingRepo add, and what does it leave alone? 2. Why does a type check on the concrete class fail with decorators?