Decorator Pattern vs Inheritance with examples

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).

Leave a Comment

tech