Repaso
Español
Design & PracticesIntermediateDP-44

Which pattern does new BufferedReader(new FileReader("a.txt")) illustrate?

Options

  1. Singleton: only one reader can exist in the whole program
  2. Decorator: BufferedReader wraps a Reader and adds buffering (Correct option)
  3. Observer: the reader notifies its listeners of every new line
  4. Prototype: the reader is cloned from an existing instance

Answer

Decorator: BufferedReader wraps another Reader and adds buffering while keeping the same interface

Why

The Decorator pattern wraps an object to add behavior, with the wrapper having the same interface as the wrapped object.

FileReader reads characters from a file; BufferedReader wraps it and adds buffering and readLine(). You can keep stacking: new GZIPInputStream(new FileInputStream(...)).

It is a flexible alternative to creating many subclasses for each combination of features.

Remember

Decorator = wrapper with the same interface that adds behavior.

Key terms

Practice this question in Repaso