I'd like to implement the Decorator design pattern using inheritance (Decorator extends Component
) because i need access to the protected fields/methods of the Component class.
The problem is that the Component class represents an algorithm, it performs some preprocessing upon construction and holds a significant amount of data. Now each time I'll be decorating a Component I'll create a new Decorator instance which will require the construction of a new (useless) Component instance performing unneeded computations and holding unneeded data.
I wanted to use interfaces instead of inheritance but then I wont be able to access Component's protected information.
Am i right to worry about the waste of resources when extending the Component class? And if so, how can i avoid it without losing access to the information i need?
One final note: I could create the Decorator instance supplying it with "dummy" data so that it will perform minimal amount of computation but this solution feels messy.
Thank you.
We use inheritance or composition to extend the behavior of an object but this is done at compile time and its applicable to all the instances of the class. We can't add any new functionality of remove any existing behavior at runtime - this is when Decorator pattern comes into picture.
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).
Disadvantages. High degree of flexibility. High complexity of software (especially decorator interface) Expansion of function of classes without inheritance. Not beginner-friendly.
The Decorator pattern is best when the decorators modify the behavior of the methods in the interface. A decorator can add methods, but added methods don't carry through when you wrap in another decorator.
I'm not sure if this would count as the decorator pattern at all actually. Sounds more like plain old inheritance.
Am i right to worry about the waste of resources when extending the Component class?
Obviously depends on how much resources you're wasting.
And if so, how can i avoid it without losing access to the information i need?
You could perhaps "open up" Component
by extending it and adding methods for accessing the protected parts you need. Then use interfaces and composition to implement a decorator for the this new class.
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