Decorator Pattern vs Inheritance with examples

Jon picture Jon · Jul 26, 2012 · Viewed 10.2k times · Source

I've been experimenting with the decorator pattern to extend functionality of code you do not want to touch for example and I see how to implement it however I am now unsure why you don't just inherit from the original class and extend that way.

I have read that the decorator pattern allows you to add functionality at runtime whereas inheritance means its there at compile time.

I don't understand this.

Could someone explain this, provide examples and explain when its better to use decorator vs inheritance.

Thanks

Answer

Razvi picture Razvi · Jul 26, 2012

Suppose you create a View class that displays your items in a certain way. Now you decide you also want a version of it which is scrollable, so you create a ScrollableView which inherits the View. Later you decide you also want a version with a border so you now need to make a BorderedView and a BorderdScrollableView.

If on the other hand you could make a decorator for each added styling. You would have the following classes:

  • View
  • ScrollableDecorator
  • BorderedDecorator

When you want a bordered scroll view you do:

new BorderedDecorator(new ScrollableDecorator(new View())).

So you can configure any combination of this with just the 3 classes. And you can add or remove them at runtime (suppose you click a button that says add border, you now wrap your view with a BorderDecorator ... while whith inheritance you need to implemented this view class if you haven't already, or you need to create a new view instance and copy all relevant data from the first view to the second view which is not as easy to do as just adding or removing wrappers).