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()

输出结果

红色的长方形

绿色的圆形

  • 应用场景: 当事物有两个维度上的表示,两个维度都可能扩展时。
  • 优点:
    • 抽象与实现分离
    • 优秀的扩展能力
相关推荐
爱昏羔4 小时前
下篇:从检索到交互 — 物流RAG问答系统与WebUI全实现
python·langchain·agent
_Jimmy_4 小时前
Agent引用数据库知识过时的增量同步方案
人工智能·python·langchain
min(a,b)5 小时前
学习第 4 天:面向对象与异常处理
python·学习·学习方法
AI大法师7 小时前
一个机场如何被做成 IP 场景:宝可梦机场的设计方法总结
大数据·人工智能·设计模式·新媒体运营
yangshicong7 小时前
第19章:AI安全防护与AI安全
人工智能·python·安全·prompt·ai编程
果汁华7 小时前
Function Calling 与 Python 实战完整指南
开发语言·网络·python
c_lb72887 小时前
2026年不同基础做量化,先找AI能参与的位置
人工智能·python
chenment9 小时前
ComfyUI 自定义节点开发:从零扩展你的图像生成工作流
python·stable diffusion
IT空门:门主9 小时前
Python 基础语法学习路线图
网络·python·学习
互联网中的一颗神经元10 小时前
小白python入门 - 25. SQL 与表设计入门
数据库·python·sql