我们为什么在装饰器模式中继承自组件类?

huangapple go评论87阅读模式
英文:

Why do we inherit from the component class in decorator pattern?

问题

在装饰者模式中,装饰者类继承自组件类,并与其存在聚合关系。聚合关系在逻辑上是存在的,但为什么要继承组件类呢?这个模式应该是用来装饰组件的,那为什么需要继承它呢?如果我们在装饰者中有一个组件对象,我们可以在运行时随意添加新功能到我们的类中,但我不明白为什么要继承。

uml图片

英文:

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.

uml photo

答案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.

huangapple
  • 本文由 发表于 2023年2月14日 02:31:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75439904.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定