Python 组合模式讲解和代码示例

简介: Python 组合模式讲解和代码示例

使用实例组合模式在 Python 代码中很常见 常用于表示与图形打交道的用户界面组件或代码的层次结构

识别方法组合可以通过将同一抽象或接口类型的实例放入树状结构的行为方法来轻松识别

概念示例

本例说明了组合设计模式的结构并重点回答了下面的问题

  • 它由哪些类组成
  • 这些类扮演了哪些角色
  • 模式中的各个元素会以何种方式相互关联

main.py: 概念示例

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 "Leaf"
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"Branch({'+'.join(results)})"
def client_code(component: Component) -> None:
    """
    The client code works with all of the components via the base interface.
    """
    print(f"RESULT: {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"RESULT: {component1.operation()}", end="")
if __name__ == "__main__":
    # This way the client code can support the simple leaf components...
    simple = Leaf()
    print("Client: I've got a simple component:")
    client_code(simple)
    print("\n")
    # ...as well as the complex composites.
    tree = Composite()
    branch1 = Composite()
    branch1.add(Leaf())
    branch1.add(Leaf())
    branch2 = Composite()
    branch2.add(Leaf())
    tree.add(branch1)
    tree.add(branch2)
    print("Client: Now I've got a composite tree:")
    client_code(tree)
    print("\n")
    print("Client: I don't need to check the components classes even when managing the tree:")
    client_code2(tree, simple)

Output.txt: 执行结果

Client: I've got a simple component:
RESULT: Leaf
Client: Now I've got a composite tree:
RESULT: Branch(Branch(Leaf+Leaf)+Branch(Leaf))
Client: I don't need to check the components classes even when managing the tree:
RESULT: Branch(Branch(Leaf+Leaf)+Branch(Leaf)+Leaf)


以上是Python 组合模式讲解和代码示例文章!

相关文章
洋码头商品 API 示例指南(Python 实现)
洋码头是国内知名跨境电商平台,提供商品搜索、详情、分类等API接口。本文详解了使用Python调用这些API的流程与代码示例,涵盖签名生成、请求处理及常见问题解决方案,适用于构建选品工具、价格监控等跨境电商应用。
|
21天前
|
VIN车辆识别码查询车五项 API 实践指南:让每一俩车有迹可循(Python代码示例)
VIN(车辆识别代码)是全球唯一的17位汽车标识码,可快速获取车架号、发动机号、品牌型号等核心信息。在二手车交易、保险理赔、维修保养等场景中,准确解析VIN有助于提升效率与风控能力。本文介绍VIN码结构、适用场景,并提供Python调用示例及优化建议,助力企业实现车辆信息自动化核验。
94 1
身份证二要素核验接口调用指南 —— Python 示例
本文介绍如何在 Python 中快速实现身份证二要素核验功能,适用于用户注册、金融风控等场景。通过阿里云市场提供的接口,可校验「姓名 + 身份证号」的一致性,并获取性别、生日、籍贯等信息。示例代码展示了从环境变量读取 APP_CODE、发送 GET 请求到解析 JSON 响应的完整流程。关键字段包括 code(1-一致,2-不一致,3-无记录)、msg 和 data。常见问题如 403 错误需检查 AppCode,超时则优化网络或设置重试机制。集成后可根据业务需求添加缓存、限流等功能提升性能。
186 4
淘宝关键词搜索商品列表API接入指南(含Python示例)
淘宝关键词搜索商品列表API是淘宝开放平台的核心接口,支持通过关键词检索商品,适用于比价、选品、市场分析等场景。接口提供丰富的筛选与排序功能,返回结构化数据,含商品ID、标题、价格、销量等信息。开发者可使用Python调用,需注意频率限制与错误处理,建议先在沙箱环境测试。
阿里旺旺私信群发工具,淘宝商家私信群发软件,python代码分享
该代码实现了完整的淘宝旺旺群发流程,包含商品采集、消息模板定制和自动化发送功能
Python爬虫开发:Cookie池与定期清除的代码实现
Python爬虫开发:Cookie池与定期清除的代码实现
一号店商品 API 示例指南(Python 实现)
本教程介绍如何使用 Python 调用一号店商品 API,涵盖商品搜索、详情、分类等接口的调用方法。内容包括注册认证、签名生成、代码实现及常见问题解决方案,并提供完整示例代码,帮助开发者快速接入一号店开放平台,构建电商工具与数据分析应用。
|
22天前
|
快递查询 API 对接指南(Python示例)
在电商与物流快速发展背景下,实时快递查询成为系统开发常见需求。本文介绍如何通过快递查询API快速集成物流信息,提升自动化水平与用户体验,并提供Python调用示例及问题解决方案。
100 0
身份验证API的实战指南(Python & PHP 示例)
本文介绍了基于身份证信息的实名认证API,适用于金融、电商、政务、医疗等领域的身份核验场景。内容包含Python与PHP调用示例及返回结果解析,助力开发者快速集成安全合规的身份验证功能。
83 0
从零复现Google Veo 3:从数据预处理到视频生成的完整Python代码实现指南
本文详细介绍了一个简化版 Veo 3 文本到视频生成模型的构建过程。首先进行了数据预处理,涵盖了去重、不安全内容过滤、质量合规性检查以及数据标注等环节。
129 5
从零复现Google Veo 3:从数据预处理到视频生成的完整Python代码实现指南

热门文章

最新文章

推荐镜像

更多
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等