4

I had this question on my test:

What kind of programming / design pattern is this:

FileReader fr = new FileReader("file.txt");
BufferedReader bf = new BufferedReader(fr);

I'm sorry for the trouble, but definitions of programming patterns are unclear for me and I don't know how to answer this question correctly.

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
Marco
  • 582
  • 1
  • 6
  • 17

2 Answers2

10

That's an example of the Decorator Pattern.

As the linked Wikipedia article states:

Decorator pattern is a design pattern that allows behaviour to be added to an existing object dynamically.

In your example, you're adding buffering to a FileReader, which provides more efficient reading than a regular, un-buffered FileReader.

Tim Pote
  • 27,191
  • 6
  • 63
  • 65
1

This is Decorator pattern. From Design Patterns book:

Intent: attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality

...

Applicability: Use Decorator

  • to add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.
  • for responsibilities that can be withdrawn.
  • when extension by subclassing is impractical. Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination. Or a class definition may be hidden or otherwise unavailable for subclassing.

In case of BufferedReader, it attaches buffering feature to FileReader.

If you want to know more about patterns, I recommend reading this book (or more lighter "Head First Patterns"). Additionally, there's brilliant answer on SO about patterns usage inside JDK -- very cool stuff!

Community
  • 1
  • 1
Victor Sorokin
  • 11,878
  • 2
  • 35
  • 51