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

输出结果

红色的长方形

绿色的圆形

  • 应用场景: 当事物有两个维度上的表示,两个维度都可能扩展时。
  • 优点:
    • 抽象与实现分离
    • 优秀的扩展能力
相关推荐
databook1 天前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室1 天前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三1 天前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427111 天前
Python之语言特点
python
刘立军1 天前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python
烛阴2 天前
【TS 设计模式完全指南】懒加载、缓存与权限控制:代理模式在 TypeScript 中的三大妙用
javascript·设计模式·typescript