英文:
Why do we inherit from the component class in decorator pattern?
问题
在装饰者模式中,装饰者类继承自组件类,并与其存在聚合关系。聚合关系在逻辑上是存在的,但为什么要继承组件类呢?这个模式应该是用来装饰组件的,那为什么需要继承它呢?如果我们在装饰者中有一个组件对象,我们可以在运行时随意添加新功能到我们的类中,但我不明白为什么要继承。
英文:
In the decorator pattern, the decorator class inherits from the component class and has an aggregation relationship with it. Well, the aggregation relationship is logical, but why should we inherit from the component? This pattern is supposed to decorate the component, so why does it need to inherit from it? If we have a component object in the decorator, we can add new functionalities to our class at runtime as we want, but I don't understand the inheritance.
答案1
得分: 1
装饰器应该实现接口,但不必继承特定的实现。我们应该能够使用装饰器而不是装饰的组件,但我们应该依赖于接口,而不是具体的类。
英文:
Decorator should implement the interface, but it doesn't have to inherit from the specific implementation. We should be able to use the decorator instead of the decorated component, but we should have a dependency on interface, not the specific class.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论