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

输出结果

红色的长方形

绿色的圆形

  • 应用场景: 当事物有两个维度上的表示,两个维度都可能扩展时。
  • 优点:
    • 抽象与实现分离
    • 优秀的扩展能力
相关推荐
孤狼warrior9 分钟前
SCTR 五次失败的安全 BN 路由器
人工智能·python·深度学习·算法·安全·yolo
天赐范式14 分钟前
天赐范式第159天:让广播走出本机——HTTP通道发出第一声
python·broadcast·urllib·http.server·天赐范式·动态运行时·http通道
keke.shengfengpolang21 分钟前
2026秋招信用风险分析岗面试:SQL和Python到底要学到什么程度才能过?
python
2601_9620990840 分钟前
python flask sqlalchemy连接数据库流程介绍
数据库·python·flask·教程·sqlalchemy
2601_9622932442 分钟前
python接口自动化(二十八)--html测试 报告——下(详解)
python·接口自动化·编码问题·htmltestrunner·报告优化
烂蜻蜓1 小时前
Flask入门教程(附录):模板渲染API——Jinja2集成全解析
后端·python·flask
2601_962387821 小时前
Python CUDA 编程 - 2 - Numba 简介
python·numpy·cuda·jit编译器·numba
智能体与具身智能9 小时前
TVA具身智能的概念、架构与应用(19)
人工智能·python·具身智能
2601_9622946110 小时前
python中range函数怎么用
python·for循环·可迭代对象·range函数·整数列表
青 春 记 忆11 小时前
零基础入门python70:Docker Compose 编排完整后端
python·后端开发