Decorator Pattern in Java IO Classes – Existence and Usage

design-patternsjava

For an assignment, I have to find out which of the Gang of Four design pattern the classes java.io.Reader and its subclasses java.io.PushbackReader, java.io.BufferedReader and java.io.FilterReader were built with.

According to this post, the design pattern would be the Decorator Pattern. This only makes sense to me if PushbackReader, BufferedReader and FilterReader can be decorated to be used at the same time, creating effectively a BufferedPushbackFilterReader. Is that the idea?

Best Answer

Yes, you can indeed decorate them like that. Just consider the following

PushbackReader pushbackBufferedReader = new PushbackReader(
     new BufferedReader(original));

That would decorate an original reader to

  • first be buffered
  • and then enable pushback/unread functionality (still the result is buffered..)

FilterReader and Reader are base classes in the hierarchy...

Related Topic