zl程序教程

您现在的位置是:首页 >  后端

当前栏目

设计模式(Python语言)----桥模式

2023-09-14 09:12:51 时间

更多信息请参考 【设计模式】

桥模式内容

将一个事务的两个维度分离,使其都可以独立地变化

桥模式中的角色

  • 抽象(Abstraction)
  • 细化抽象(Refined Abstraction)
  • 实现者(Implementor)
  • 具体实现者(concrete Implementor)

桥模式的使用场景

  • 当事务有两个维度上的表现,两个维度都有可能扩展时

桥模式的优点

  • 抽象和实现相分离
  • 优秀的扩展能力

桥模式实例

(1)未使用桥模式时,类设计如下,即形状和颜色两个维度都变化时,类的数量是很多的

class Shape:
    pass

class Line(Shape):
    pass

class Rectangle(Shape):
    pass

class Circle(Shape):
    pass

class RedLine(Line):
    pass

class GreenLine(Line):
    pass

class BlueLine(Line):
    pass

class RedRectangle(Rectangle):
    pass

class GreeRectangle(Rectangle):
    pass

class BlueRectangel(Rectangle):
    pass

class RedCircle(Circle):
    pass

class GreenCircle(Circle):
    pass

class BlueCircle(Circle):
    pass

(2)使用桥模式时,类代码如下:

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 Red(Color):
    def paint(self,shape):
        print(f"红色的{shape.name}")

class Green(Color):
    def paint(self,shape):
        print(f"绿色的{shape.name}")

class Blue(Color):
    def paint(self,shape):
        print(f"蓝色的{shape.name}")

class Rectangle(Shape):
    name="长方形"
    def draw(self):
        self.color.paint(self)

class Circle(Shape):
    name="圆形"
    def draw(self):
        self.color.paint(self)

class Line(Shape):
    name="直线"
    def draw(self):
        self.color.paint(self)

if __name__=="__main__":
    shap1=Rectangle(Red())
    shap1.draw()

    shap2=Circle(Blue())
    shap2.draw()

    shap3=Line(Green())
    shap3.draw()

执行结果如下:

红色的长方形
蓝色的圆形
绿色的直线

如此,则颜色和形状两个维度可以自由变化,然后进行自由组合即可完成不同颜色的不同形状

推荐阅读

设计模式(Python语言)----面向对象设计SOLID原则

设计模式(Python语言)----设计模式分类

设计模式(Python语言)----简单工厂模式

设计模式(Python语言)----工厂方法模式

设计模式(Python语言)----抽象工厂模式

设计模式(Python语言)----建造者模式

设计模式(Python语言)----单例模式

设计模式(Python语言)----适配器模式

设计模式(Python语言)----桥模式

设计模式(Python语言)----组合模式

设计模式(Python语言)----外观模式

设计模式(Python语言)----代理模式

设计模式(Python语言)----责任链模式

设计模式(Python语言)----观察者模式

设计模式(Python语言)----策略模式

设计模式(Python语言)----模板方法模式