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

输出结果

红色的长方形

绿色的圆形

  • 应用场景: 当事物有两个维度上的表示,两个维度都可能扩展时。
  • 优点:
    • 抽象与实现分离
    • 优秀的扩展能力
相关推荐
傻啦嘿哟11 分钟前
Python实现PDF文档高效转换为HTML文件:从基础到进阶的完整指南
python·pdf·html
明洞日记1 小时前
【设计模式手册011】享元模式 - 共享细粒度对象的高效之道
java·设计模式·享元模式
天下无敌笨笨熊1 小时前
ES作为向量库研究
大数据·python·elasticsearch
数据知道1 小时前
FastAPI项目:从零到一搭建一个网站导航系统
python·mysql·fastapi·python web·python项目
帅中的小灰灰1 小时前
C++编程观察者设计模式
数据库·c++·设计模式
程序员爱钓鱼2 小时前
Python 编程实战 · 进阶与职业发展:数据分析与 AI(Pandas、NumPy、Scikit-learn)
后端·python·trae
软件开发技术深度爱好者2 小时前
Python库/包/模块管理工具
开发语言·python
程序员爱钓鱼2 小时前
Python 编程实战 · 进阶与职业发展:Web 全栈(Django / FastAPI)
后端·python·trae
郝学胜-神的一滴2 小时前
Python中一切皆对象:深入理解Python的对象模型
开发语言·python·程序人生·个人开发
阿波罗尼亚3 小时前
Head First设计模式(六) 设计原则 命令模式
设计模式·命令模式