Decorator pattern versus sub classing

Gainster picture Gainster · Jan 30, 2011 · Viewed 21.6k times · Source

I can solve the problem of adding functionality by adding sub classing then why should I use decorator pattern what's the real advantage of decorator pattern ?

Answer

sloth picture sloth · Jan 30, 2011

from Decorator pattern at wikipedia

The decorator pattern can be used to make it possible to extend (decorate) the functionality of a certain object at runtime.

The whole point of decorator pattern is to dynamically add additional behaviour/functionality, which is of course not possible at design time.

from the same article:

The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time, and the change affects all instances of the original class; decorating can provide new behavior at runtime for individual objects.