首页 > 解决方案 > 装饰器模式是否违反了 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()

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

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

有人可以提供一些澄清吗?

标签: pythonoopdesign-patternssolid-principlesclean-architecture

解决方案


我将这个问题标记为已解决,因为上面对我原来的问题的评论是关于向类添加方法违反了 SOLID 原则的事实。


推荐阅读