組合模式编整,像樹的枝和葉一樣進(jìn)行組合讼稚。
class Branch(object):
def __init__(self):
super().__init__()
self.branch = []
self.leaf = []
def add(self, obj):
if type(obj) == Branch:
self.branch.append(obj)
else:
self.leaf.append(obj)
def __str__(self):
content = ""
for branch in self.branch:
content += str(branch) + '\n'
return "branch" + str([str(leaf) for leaf in self.leaf]) + '\n' + content
class Leaf(object):
def __init__(self):
super().__init__()
def add(self):
pass
def __str__(self):
return "leaf"
def main():
branch_a = Branch()
branch_a.add(Leaf())
branch_a.add(Leaf())
branch_b = Branch()
branch_b.add(Leaf())
branch_b.add(branch_a)
branch_main = Branch()
branch_main.add(branch_b)
print(branch_main)
if __name__ == '__main__':
main()