简体   繁体   中英

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.

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.

Clearly, your Component class is not designed "to be decorated". Have you thought of refactoring it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM