【发布时间】:2015-07-28 04:28:13
【问题描述】:
我见过的大多数复合设计模式的描述都有 Composite 实现 add() 和 remove() 方法,而在 Leaf 对象中未实现这些方法。例如,该主题的Wiki Page 中的图表暗示了这一点,这与GoF图表或多或少相同。
关于在父 Component 类中实现这些,GoF 有以下说法:
在类层次结构的根部定义子管理接口为您提供了透明度,因为您可以统一对待所有组件。但是,这会损害您的安全,因为客户端可能会尝试做一些无意义的事情,例如从叶子中添加和删除对象。
我同意拥有Leaf 实现remove() 处理起来很奇怪。 (你删除自己吗?你必须实现某种NullLeaf 对象吗?)但是由于模式的重点是使Leafs 和Composites 的行为方式相同,我不明白为什么@ 987654332@可以在Component中实现。
我的问题:为什么Component至少不能实现add()?这样做会违反任何关键设计原则吗?这样做是否不再使这成为一种复合设计模式?下面是一个 Python 示例,它抓住了我试图在自己的工作中实现的精髓:
class Component:
def add(self, other):
# in Python, may be more natural to define __add__
c = Composite()
c.children = self.children + other.children
return c
class Leaf(Component):
def __init__(self):
self.children = [self] # possibly strange?
def operation(self):
# operation specific to this leaf
class Composite(Component):
def __init__(self):
self.children = []
def operation(self):
for child in self.children:
child.operation()
带有“示例用法”:
>>> l1 = Leaf()
>>> l2 = Leaf()
>>> c = l1.add(l2) # c is a `Composite` instance
>>> c.operation()
【问题讨论】:
标签: oop design-patterns