【Python设计模式】桥模式

花间影清欢课程 2024-03-27 11:09:42
桥模式内容: 将一个事物的两个维度分离,使其都可以独立地变化角色: - 抽象(Abstraction) - 细化抽象(RefinedAbstraction) - 实现者(Implementor) - 具体实现者(ConcreteImplementor)应用场景: 当事物有两个维度上的表现,两个维度都需要扩展时优点: 1. 抽象与实现分离 2. 优秀的扩展能力

示例

from abc import ABCMeta, abstractmethodclass Shape(metaclass=ABCMeta): def __init__(self, color): self.color = color @abstractmethod def draw(self): passclass Color(metaclass=ABCMeta): @abstractmethod def paint(self, shape): passclass Rectangle(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(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}')# client# 红色矩形shape = Rectangle(Red())shape.draw()# 绿色圆形shape = Circle(Green())shape.draw()# 蓝色圆形shape = Circle(Blue())shape.draw()

运行结果

0 阅读:0