假设我们有这样一个组件类:
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()
的行为,我们仍然必须定义它,而不是依赖于超类方法,否则将调用组件的another_operation()
而不是ChildComponent的方法,并且您将面临一个糟糕的混合情况
然而,如果我们要这样做,那么每当组件类获得一个新方法时,我们也必须将它添加到decorator中,这不符合接口隔离原则。因此,我们要么违反坚实的原则,维护两倍于我们需要的代码量,要么冒着使用错误方法的风险,对那些我们没有在decorator中显式重写的方法
有人能澄清一下吗
我将这个问题标记为已解决,因为我在上面的原始问题上发表了评论,即向类中添加方法违反了坚实的原则
相关问题 更多 >
编程相关推荐