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

输出结果

红色的长方形

绿色的圆形

  • 应用场景: 当事物有两个维度上的表示,两个维度都可能扩展时。
  • 优点:
    • 抽象与实现分离
    • 优秀的扩展能力
相关推荐
jyOverQ16 小时前
LangGraph:子图动态路由与 Agent 工作流设计
python·langchain
晴天1616 小时前
Gradio 与 Streamlit:Python 快速构建 Web 应用的双子星-Day28
开发语言·前端·python
苏灿烤鱼16 小时前
把求职写成工作流,公开 fork 为什么会把简历写进仓库?
python·typescript·claude
whcyhhh16 小时前
头歌实践教学平台:数据科学与大数据技术导论(十)
大数据·开发语言·python
华研前沿标杆游学20 小时前
华为松山湖高阶研学|企业数字化转型游学攻略
python
Data_Journal1 天前
用于网页抓取的 Node-unblocker
大数据·开发语言·数据库·python·scrapy
豆角焖肉1 天前
SSM 聚合项目搭建:多 Maven 模块项目
开发语言·python·pycharm
青 春 记 忆1 天前
零基础入门python20:Flask配置、扩展和蓝图拆分
python·flask·后端开发
m0_380743871 天前
为 OpenAI 兼容接口配置教程
开发语言·python·node.js
leisoo80971 天前
ig50数据落盘ClickHousevsTimescaleDBvsDuckDB实测对比 IG50免费开源股票数据API接口
开发语言·jvm·数据库·python·json