桥模式
概述
对象
- 抽象(Abstraction)
- 细化抽象(RefindAbstraction)
- 实现者(Implementor)
- 具体实现者(ConcreteImplementor)
适用场景
- 当事物有两个维度上的表现, 并且在每个维度都有可能扩展时
例子
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 Rectangle(Shape):
name = "矩形"
def draw(self):
self.color.paint(self)
class Circular(Shape):
name = "圆"
def draw(self):
self.color.paint(self)
class Red(Color):
name = "红色"
def paint(self, shape):
print(f"{Red.name}的{shape.name}")
class Blue(Color):
name = "蓝色"
def paint(self, shape):
print(f"{Blue.name}的{shape.name}")
rectangle = Rectangle(Red())
rectangle.draw()
优点