装饰器模式是否违反了SOLID原则



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

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()

根据我的理解,即使我们没有在decorator中修改another_operation()的行为,我们仍然必须定义它,而不是依赖于超类方法,否则将调用Component的another_operation()而不是ChildComponent的方法,并且您将面临糟糕的混合情况。

然而,如果我们要这样做,那么每当Component类获得一个新方法时,我们都必须将其添加到decorator中,这不符合接口分离原则。因此,我们要么必须违反SOLID原则,并维护两倍于我们需要的代码量,要么冒着使用错误方法的风险来处理那些我们在decorator中没有明确覆盖的方法。

有人能澄清一下吗?

我将这个问题标记为已解决,因为上面对我的原始问题的评论是,向类中添加方法无论如何都违反了SOLID原则。

最新更新