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
With decorators, responsibilities can be added and removed at run-time simply by attaching and detaching them. In contrast, inheritance requires creating a new class for each additional responsibility (e.g., BorderedScrollableTextView, BorderedTextView).
The decorator pattern provides a flexible alternative to inheritance for extending objects functionality. This pattern is designed in a way that multiple decorators can be stacked on top of each other, each adding new functionality.
The decorator design pattern is a structural pattern, which provides a wrapper to the existing class. Decorator design pattern uses abstract classes or interfaces with the composition to implement the wrapper.
This pattern creates a decorator class which wraps the original class and provides additional functionality keeping class methods signature intact. We are demonstrating the use of decorator pattern via following example in which we will decorate a shape with some color without alter shape class.
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:
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With