Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorator design pattern using inheritance vs interfaces

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.

like image 946
yurib Avatar asked May 31 '11 10:05

yurib


People also ask

Does Decorator design pattern use inheritance?

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.

What is difference between decorator and inheritance?

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

What is a disadvantage of the decorator pattern?

Disadvantages. High degree of flexibility. High complexity of software (especially decorator interface) Expansion of function of classes without inheritance. Not beginner-friendly.

When would you use the Decorator design pattern?

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.


1 Answers

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.

like image 63
aioobe Avatar answered Oct 13 '22 07:10

aioobe