【发布时间】: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