使用继承vs接口的装饰设计模式 [英] Decorator design pattern using inheritance vs interfaces

查看:101
本文介绍了使用继承vs接口的装饰设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用继承( Decorator extends Component )实现Decorator设计模式,因为我需要访问Component类的受保护的字段/方法。



问题是Component类代表一个算法,它在构造时执行一些预处理,并保存大量的数据。现在每当我装饰一个组件时,我将创建一个新的Decorator实例,这将需要构造一个新的(无用的)组件实例,执行不必要的计算并保存不需要的数据。



我想使用接口而不是继承,但是我无法访问组件的受保护的信息。在扩展Component类时,我有权担心资源浪费吗?如果是这样,我怎么可以避免它而不会访问我需要的信息?



最后一个注意事项:我可以创建装饰器实例,为其提供虚拟数据所以它将执行最少的计算量,但这个解决方案感觉很杂乱。



谢谢。

解决方案

我不知道这是否会被视为装饰图案。听起来更像是普通的老式继承。


扩展Component类时,我是否担心浪费资源?


显然取决于你浪费了多少资源。


如果是,如何避免它,而不会访问我需要的信息?


您可以通过扩展它来添加方法来打开组件您需要的保护部件然后使用接口和组合来实现这个新类的装饰器。


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.

这篇关于使用继承vs接口的装饰设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆