首页 > 编程语言 >Python: Composite Pattern

Python: Composite Pattern

时间:2022-10-21 22:35:17浏览次数:34  
标签:Python component self Component Composite Pattern children def

DuComposite.py

# 组合模式 Composite  Pattern
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List


class Component(ABC):
    """
    The base Component class declares common operations for both simple and
    complex objects of a composition.
    """

    @property
    def parent(self) -> Component:
        return self._parent

    @parent.setter
    def parent(self, parent: Component):
        """
        Optionally, the base Component can declare an interface for setting and
        accessing a parent of the component in a tree structure. It can also
        provide some default implementation for these methods.
        """

        self._parent = parent

    """
    In some cases, it would be beneficial to define the child-management
    operations right in the base Component class. This way, you won't need to
    expose any concrete component classes to the client code, even during the
    object tree assembly. The downside is that these methods will be empty for
    the leaf-level components.
    """

    def add(self, component: Component) -> None:
        pass

    def remove(self, component: Component) -> None:
        pass

    def is_composite(self) -> bool:
        """
        You can provide a method that lets the client code figure out whether a
        component can bear children.
        """

        return False

    @abstractmethod
    def operation(self) -> str:
        """
        The base Component may implement some default behavior or leave it to
        concrete classes (by declaring the method containing the behavior as
        "abstract").
        """

        pass


class Leaf(Component):
    """
    The Leaf class represents the end objects of a composition. A leaf can't
    have any children.

    Usually, it's the Leaf objects that do the actual work, whereas Composite
    objects only delegate to their sub-components.
    """

    def operation(self) -> str:
        return "叶子"


class Composite(Component):
    """
    The Composite class represents the complex components that may have
    children. Usually, the Composite objects delegate the actual work to their
    children and then "sum-up" the result.
    """

    def __init__(self) -> None:
        self._children: List[Component] = []

    """
    A composite object can add or remove other components (both simple or
    complex) to or from its child list.
    """

    def add(self, component: Component) -> None:
        self._children.append(component)
        component.parent = self

    def remove(self, component: Component) -> None:
        self._children.remove(component)
        component.parent = None

    def is_composite(self) -> bool:
        return True

    def operation(self) -> str:
        """
        The Composite executes its primary logic in a particular way. It
        traverses recursively through all its children, collecting and summing
        their results. Since the composite's children pass these calls to their
        children and so forth, the whole object tree is traversed as a result.
        """

        results = []
        for child in self._children:
            results.append(child.operation())
        return f"分枝({'+'.join(results)})"


def client_code(component: Component) -> None:
    """
    The client code works with all of the components via the base interface.
    """

    print(f"结果: {component.operation()}", end="")


def client_code2(component1: Component, component2: Component) -> None:
    """
    Thanks to the fact that the child-management operations are declared in the
    base Component class, the client code can work with any component, simple or
    complex, without depending on their concrete classes.
    """

    if component1.is_composite():
        component1.add(component2)

    print(f"结果: {component1.operation()}", end="")

  

main.py

调用:

# 组合模式 Composite  Pattern
# This way the client code can support the simple leaf components...
simple = DuComposite.Leaf()
print("客户端: 我有一个简单的组件:")
DuComposite.client_code(simple)
print("\n")

# ...as well as the complex composites.
tree = DuComposite.Composite()

branch1 = DuComposite.Composite()
branch1.add(DuComposite.Leaf())
branch1.add(DuComposite.Leaf())

branch2 = DuComposite.Composite()
branch2.add(DuComposite.Leaf())

tree.add(branch1)
tree.add(branch2)

print("客户端: 现在我有了一个合成树:")
DuComposite.client_code(tree)
print("\n")

print("客户端: 我不需要检查组件类,即使在管理树:")
DuComposite.client_code2(tree, simple)

  

输出:

客户端: 我有一个简单的组件:
结果: 叶子

客户端: 现在我有了一个合成树:
结果: 分枝(分枝(叶子+叶子)+分枝(叶子))

客户端: 我不需要检查组件类,即使在管理树:
结果: 分枝(分枝(叶子+叶子)+分枝(叶子)+叶子)

 

 

 

 

  


标签:Python,component,self,Component,Composite,Pattern,children,def
From: https://www.cnblogs.com/geovindu/p/16814978.html

相关文章

  • 3.Python 注释和函数使用
    注释三总:单行注释直接#+内容多行注释三个单引号括起来的内容指定编码注释可以指定文件的中文编码例:#作者:咸瑜#代码时间:2022/10/1715:57''''多行注......
  • 备战python蓝桥杯等级考试系列1.输出hello world
    ​ ​编辑​编辑获取​python从初级到高级学习资料......
  • Python学习:列表和字典练习题
    找出列表list中大于100的值,给字典dic的k1键,小于等于100的值,给字典dic的k2键'''提示:创建字典的两种方式ex:'''v1=[2,3,4,5,]v2=88dic1={'k1':v1,'k2':v2,}......
  • python系列归并排序图文详解
    ​ 算法原理:      改归并排序将序列折半分成两个子序列,然后继续拆分,直到每个序列只有一个数据时,再将各个子序列排序后合并叠加。直到所有子序列都合并,排序完成。......
  • 使用vscode创建我的第一个python程序
    软件配置:首先打开vscode,点击红色方框按钮:  在搜索栏输入【python】,并下载python插件:   如果觉得软件是英文不好理解可以下一个中文插件:   创建 第......
  • Python教程Day06-字符串
    一、认识字符串字符串是Python中最常用的数据类型。我们一般使用引号来创建字符串。创建字符串很简单,只要为变量分配一个值即可。a='helloworld'b="abcdefg"print(......
  • Python教程Day07-列表
    一、列表的应用场景当我们需要存一个数据时,可以直接使用变量,但是,当我们要存储100个,设置更多的时候,变量肯定不行,这时候我们要用啥?此时列表就有它的用武之地了,一次性存储多个......
  • 【python】这么**得小姐姐网~不敢赶紧采集一波~免得它没了
    前言大家早好、午好、晚好吖~ 今天我们来采集一下这个小姐姐网~  环境使用:Python3.8解释器Pycharm编辑器importreimportrequests>>>pip......
  • 如何快速在Ubuntu上搭建python环境?
    如何快速在Ubuntu上搭建python环境?一、准备好python源码包使用curl命令获取python源码包的过程很缓慢且容易失败,因此提前去官网下载好后放在本地是最好的办法。二、启动......
  • 正则表达式(C、C++、Python、Shell)
    撰写本文档的初衷本来是想介绍正则表达式怎么写,但是百度一搜,正则表达式的教程的质量已经相当高,我便不在班门弄斧了。正则表达式是一种方法,在不同的语言中,它的应用样式可能......