示例
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()运行结果
