Friday, March 13, 2009

What is the difference between inheritance and decorator design

Question :What is the difference between inheritance and decorator design
pattern? (DesignPatterns)

Answer :Decorators represent a powerful alternative to inheritance. Inheritance
lets you add functionality to classes
at compile time, decorators let you add functionality to objects at runtime.
For example
1. FileReader frdr = new FileReader(filename);
2. LineNumberReader lrdr = new LineNumberReader(frdr);
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.

No comments: