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

输出结果

红色的长方形

绿色的圆形

  • 应用场景: 当事物有两个维度上的表示,两个维度都可能扩展时。
  • 优点:
    • 抽象与实现分离
    • 优秀的扩展能力
相关推荐
法海爱捉虫16 小时前
小微企业 / 货代专用快递打单工具,适配热敏 / A4 打印机 功能设计
python
asdzx6716 小时前
Python 优雅解析 Excel:从原生行列到强类型对象的三层数据结构演进
数据结构·python·excel
码云骑士16 小时前
26-密码密钥配置管理-env文件与多环境隔离策略
python
装不满的克莱因瓶16 小时前
掌握基于YOLO v5实现车牌目标检测任务的完整流程——从数据到部署的工业级实践
人工智能·python·深度学习·yolo·目标检测·计算机视觉·目标跟踪
骑士雄师16 小时前
1.1 rag开发基础配置
python
码云骑士16 小时前
25-数据库连接池-Django连接复用与连接数上限控制
数据库·python·django
叫我:松哥16 小时前
基于Flask的在线考试刷题系统设计与实现,集智能练习、过程追踪、深度分析与个性化引导
数据库·人工智能·后端·python·flask·boostrap
techdashen16 小时前
CPython 仓库 Top 100 贡献者深度分析
python
码云骑士16 小时前
22-接手Django老项目(下)-读懂urls路由树与架构脉络
python·架构·django