Which pattern does new BufferedReader(new FileReader("a.txt")) illustrate?
Options
- Singleton: only one reader can exist in the whole program
- Decorator: BufferedReader wraps a Reader and adds buffering (Correct option)
- Observer: the reader notifies its listeners of every new line
- 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.