赞
踩
组合模式是一种结构型设计模式, 你可以使用它将对象组合成树状结构, 并且能像使用独立对象一样使用它们。
- #!/usr/bin/env python
- # -*- coding: UTF-8 -*-
- __doc__ = """
- 组合模式
- 例:生成具有树状结构的食品分类,并遍历输出
- """
-
- from abc import ABC, abstractmethod
-
-
- class Component(ABC):
- """抽象基类"""
-
- @abstractmethod
- def operation(self):
- pass
-
-
- class Leaf(Component):
- """叶子节点类"""
-
- def __init__(self, name):
- self.name = name
-
- def operation(self, indent=""):
- return f"{indent}- {self.name}"
-
-
- class Composite(Component):
- """容器节点类"""
-
- def __init__(self, name):
- self.name = name
- self.children = []
-
- def add(self, component):
- self.children.append(component)
-
- def remove(self, component):
- self.children.remove(component)
-
- def operation(self, indent=""):
- result = [f"{indent}+ {self.name}"]
- for child in self.children:
- result.append(child.operation(indent + " "))
- return "\n".join(result)
-
-
- if __name__ == "__main__":
- """
- + 食品
- + 水果
- - 苹果
- - 香蕉
- + 蔬菜
- - 西红柿
- - 黄瓜
- """
- fruit = Composite("水果")
- fruit.add(Leaf("苹果"))
- fruit.add(Leaf("香蕉"))
-
- vegetable = Composite("蔬菜")
- vegetable.add(Leaf("西红柿"))
- vegetable.add(Leaf("黄瓜"))
-
- food = Composite("食品")
- food.add(fruit)
- food.add(vegetable)
-
- print(food.operation())
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。