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

输出结果

红色的长方形

绿色的圆形

  • 应用场景: 当事物有两个维度上的表示,两个维度都可能扩展时。
  • 优点:
    • 抽象与实现分离
    • 优秀的扩展能力
相关推荐
坐吃山猪43 分钟前
Python进度条
linux·服务器·python
l1t1 小时前
四种python工具包用SQL查询csv和parquet文件的方法比较
大数据·python·sql
清水白石0081 小时前
Python 并发三剑客:多线程、多进程与协程的实战抉择
java·服务器·python
2301_793804691 小时前
更优雅的测试:Pytest框架入门
jvm·数据库·python
dinl_vin1 小时前
python:常用的基础工具包
开发语言·python
wefly20172 小时前
无需安装、开箱即用!m3u8live.cn 在线 HLS 播放器,调试直播流效率翻倍
前端·后端·python·前端开发工具·后端开发工具
2301_815482932 小时前
用Python实现自动化的Web测试(Selenium)
jvm·数据库·python
将心ONE2 小时前
melo tts安装使用
python
宸翰3 小时前
Python学习:年轻人的第一个入门Python项目(FastAPI版)
后端·python
AsDuang3 小时前
Python 3.12 MagicMethods - 55 - __irshift__
开发语言·python