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

输出结果

红色的长方形

绿色的圆形

  • 应用场景: 当事物有两个维度上的表示,两个维度都可能扩展时。
  • 优点:
    • 抽象与实现分离
    • 优秀的扩展能力
相关推荐
空影星4 分钟前
Tablecruncher,一款轻量级CSV编辑器
python·编辑器·电脑·智能硬件
bin915319 分钟前
当AI开始‘映射‘用户数据:初级Python开发者的创意‘高阶函数‘如何避免被‘化简‘?—— 老码农的函数式幽默
开发语言·人工智能·python·工具·ai工具
万粉变现经纪人1 小时前
如何解决 pip install -r requirements.txt 私有仓库认证失败 401 Unauthorized 问题
开发语言·python·scrapy·flask·beautifulsoup·pandas·pip
懂得节能嘛.1 小时前
【设计模式】Java规则树重构复杂业务逻辑
java·开发语言·设计模式
tan77º1 小时前
【项目】基于多设计模式下的同步&异步日志系统 - 项目介绍与前置知识
linux·c++·设计模式
你才是向阳花2 小时前
如何用python来做小游戏
开发语言·python·pygame
'需尽欢'3 小时前
基于 Flask+Vue+MySQL的研学网站
python·mysql·flask
新子y4 小时前
【小白笔记】最大交换 (Maximum Swap)问题
笔记·python
程序员爱钓鱼5 小时前
Python编程实战 · 基础入门篇 | Python的缩进与代码块
后端·python
pr_note6 小时前
python|if判断语法对比
python