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

输出结果

红色的长方形

绿色的圆形

  • 应用场景: 当事物有两个维度上的表示,两个维度都可能扩展时。
  • 优点:
    • 抽象与实现分离
    • 优秀的扩展能力
相关推荐
数据科学小丫1 小时前
Python 数据存储操作_数据存储、补充知识点:Python 与 MySQL交互
数据库·python·mysql
Knight_AL1 小时前
Nacos 启动问题 Failed to create database ’D:\nacos\nacos\data\derby-data’
开发语言·数据库·python
查古穆3 小时前
python进阶-Pydantic模型
开发语言·python
佳木逢钺3 小时前
PyQt界面美化系统高级工具库:打造现代化桌面应用的完整指南
python·pyqt
工頁光軍3 小时前
基于Python的Milvus完整使用案例
开发语言·python·milvus
Csvn3 小时前
特殊方法与运算符重载
python
xht08324 小时前
PHP vs Python:编程语言终极对决
开发语言·python·php
2401_879693874 小时前
使用Python控制Arduino或树莓派
jvm·数据库·python
查古穆4 小时前
python进阶-推导式
开发语言·python