Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question

migrated from stackoverflow.com Jun 19 '11 at 15:14

This question came from our site for professional and enthusiast programmers.

    
Look at the constructors of those classes. Do they allow you to to stack, e.g. the Buffered nature on top of the Filter nature? –  Kilian Foth Jun 19 '11 at 10:33
    
@Kilian Foth: Looks like it. –  ryyst Jun 19 '11 at 10:38
add comment

2 Answers

The decorator pattern applies here because BufferedReader wraps a Reader - it's still a Reader (it has all the methods of Reader), but it has more "bells and whistles" (more methods).

Here's an example showing how one class "decorates" the functionality of the one it wraps, and you can chain them up to keep decorating:

        new BufferedReader(new FileReader(new File("some.file")));
share|improve this answer
add comment
up vote 8 down vote accepted

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...

share|improve this answer
    
And BufferedReader, FilterReader and PushbackReader are decorators of Reader, right? –  ryyst Jun 19 '11 at 10:39
1  
Yes, that's correct. –  duffymo Jun 19 '11 at 10:41
1  
Yes - BufferedReader make the underlying reader buffered, PushbackReader enables you to 'unread' data from the reader etc... –  dcn Jun 19 '11 at 10:41
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.