【问题标题】:Does the decorator pattern violate SOLID principles?装饰器模式是否违反了 SOLID 原则?
【发布时间】:2021-03-23 10:53:47
【问题描述】:

假设我们有一个这样的组件类:

class Component:
    def operation(self) -> str:
        return f"Performing operation"

    def another_operation(self) -> str:
        return f"Performing another operation"

然后我们有一个子组件覆盖了它的两个方法:

class ChildComponent(Component):
    def operation(self) -> str:
        return f"Performing operation differently"

    def another_operation(self) -> str:
        return f"Performing another operation differently"

然后我们可以定义一个修饰器来修改操作的行为:

class Decorator(Component):
    _component: Component = None

    def __init__(self, component: Component) -> None:
        self._component = component

    def operation(self) -> str:
        return f"Decorated...({self._component.operation()})"

    def another_operation(self) -> str:
        return self._component.another_operation()

据我了解,即使我们没有修改装饰器中another_operation() 的行为,我们仍然必须定义它而不是依赖超类方法,否则将调用Component 的another_operation() 而不是ChildComponent 的方法,而你你手上会有一个糟糕的混合情况。

但是,如果我们要这样做,那么任何时候 Component 类获得一个新方法,我们都必须将它也添加到装饰器中,这不符合接口隔离原则。因此,我们要么必须违反 SOLID 原则并维护两倍于我们需要的代码量,要么冒险使用错误的方法来处理我们没有在装饰器中明确覆盖的方法。

有人可以澄清一下吗?

【问题讨论】:

  • 请注意,Python 允许您以自动转发操作的方式实现装饰器模式,例如使用__getattr__。您是在询问一般的装饰器模式,还是此处显示的实现?
  • 我在问一般性问题,但您能否将我链接到有关此转发的更多信息?我仍在从 Java 适应 Python。
  • 查看Implementing the decorator pattern in Python 以获取使用__getattr__ 的示例。
  • 向Component添加方法违反了开放/封闭原则,无论是否有装饰器。

标签: python oop design-patterns solid-principles clean-architecture


【解决方案1】:

我将这个问题标记为已解决,因为我在上面的原始问题上发表了评论,即向类添加方法违反了 SOLID 原则。

【讨论】:

  • 只需将问题标记为已删除,以确保您不会因此而惹上麻烦
  • 这没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方留下评论。 - From Review
猜你喜欢
  • 2016-12-29
  • 2010-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-01
  • 2018-11-13
  • 1970-01-01
相关资源
最近更新 更多