7.python设计模式【桥结模式】

  • 内容:将一个事物的两个维度分离,使其都可以独立变化
  • 角色:
    • 抽象(Abstraction)
    • 细化抽象(RefinedAbstraction)
    • 实现者(Implementor)
    • 具体实现者(ConcreteImplementor)
  • UML图
  • 举个例子
    需求:要求绘制一个图像,图形和颜色相互分离,并且可以相互组合
python 复制代码
from abc import ABCMeta, abstractmethod


# 创建抽象类
class Shape(metaclass=ABCMeta):
    def __init__(self, color):
        self.color = color

    @abstractmethod
    def draw(self):
        pass


class Color(metaclass=ABCMeta):
    @abstractmethod
    def paint(self, shape):
        pass


# 创建具体实现类
class Retangle(Shape):
    name = "长方形"

    def draw(self):
        # 长方形逻辑
        self.color.paint(self)


class Circle(Shape):
    name = "圆形"

    def draw(self):
        # 圆形逻辑
        self.color.paint(self)


class Red(Color):
    def paint(self, shape):
        print("红色的%s" % shape.name)


class Green(Color):
    def paint(self, shape):
        print("绿色的%s" % shape.name)


shape = Retangle(Red())
shape.draw()

shape2 = Circle(Green())
shape2.draw()

输出结果

红色的长方形

绿色的圆形

  • 应用场景: 当事物有两个维度上的表示,两个维度都可能扩展时。
  • 优点:
    • 抽象与实现分离
    • 优秀的扩展能力
相关推荐
AI逐月27 分钟前
解决 ComfyUI 插件安装后 Nanobind 报错问题:soxr 版本冲突原理解读
开发语言·python
AC赳赳老秦27 分钟前
Windows 系统 OpenClaw 执行策略报错及管理员权限设置深度解析与实操指南
运维·人工智能·python·django·自动化·媒体·openclaw
软件开发技术深度爱好者1 小时前
用python + pillow实现GUI界面图片GUI处理工具
开发语言·python
FreakStudio1 小时前
ESP32 实现在线动态安装库和自动依赖安装-使用uPyPI包管理平台
python·单片机·嵌入式·面向对象·电子diy·sourcetrail
武藤一雄1 小时前
C# 异步回调与等待机制
前端·microsoft·设计模式·微软·c#·.netcore
别抢我的锅包肉1 小时前
【FastAPI】 响应类型详解:从默认 JSON 到自定义响应
python·fastapi
智算菩萨2 小时前
【Tkinter】15 样式与主题深度解析:ttk 主题系统、Style 对象与跨平台样式管理实战
开发语言·python·ui·ai编程·tkinter
weixin_419349792 小时前
Python 项目中生成 requirements.txt 文件
开发语言·python
第一程序员2 小时前
Python与区块链:非科班转码者的指南
python·github
liu****2 小时前
LangChain-AI应用开发框架(六)
人工智能·python·langchain·大模型应用·本地部署大模型