Monday, February 28, 2011

Decorator pattern examples

Example 1. Instantiating I/O decorators

FileReader       frdr = new FileReader(filename);
LineNumberReader lrdr = new LineNumberReader(frdr);

The preceding code creates a reader -- lrdr -- that reads from a file and tracks line numbers. Line 1 creates a file reader (frdr), and line 2 adds line-number tracking.

At runtime, decorators forward method calls to the objects they decorate. For example, in the code above, the line number reader, lrdr, forwards method calls to the file reader, frdr. Decorators add functionality either before or after forwarding to the object they decorate; for example, our line number reader tracks the current line number as it reads from an input stream.

Alternatively, of course, you could write Example 1 like this:

LineNumberReader lrdr = new LineNumberReader(new FileReader(filename));

Example 2. Using I/O decorators

try {
LineNumberReader lrdr = new LineNumberReader(new FileReader(filename));
for(String line; (line = lrdr.readLine()) != null;)rticle.txt {
System.out.print(lrdr.getLineNumber() + ":\t" + line);
catch( fnfx) {
catch( iox) {

Decorators represent a powerful alternative to inheritance. Whereas inheritance lets you add functionality to classes at compile time, decorators let you add functionality to objects at runtime.

No comments:

Post a Comment