将抽象化和实现化结构,使得二者可以独立变化

使用场景

一个类有两种独立变化的维度

Demo

  1. """
  2. 桥接模式
  3. """
  4. class DrawAPI:
  5. def draw_circle(self, *args, **kwargs):
  6. raise NotImplementedError
  7. class RedCircle(DrawAPI):
  8. def draw_circle(self, radius, x, y):
  9. print(f"drawing circle red : {radius}, {x} ,{y}")
  10. class GreenCircle(DrawAPI):
  11. def draw_circle(self, radius, x, y):
  12. print(f"drawing circle green : {radius}, {x} ,{y}")
  13. class Shape:
  14. def __init__(self, draw_api: DrawAPI):
  15. self.draw_api = draw_api
  16. def draw(self, radius, x, y):
  17. raise NotImplementedError
  18. class Circle(Shape):
  19. def draw(self, radius, x, y):
  20. self.draw_api.draw_circle(radius, x, y)
  21. if __name__ == '__main__':
  22. red_circle = Circle(RedCircle())
  23. green_circle = Circle(GreenCircle())
  24. red_circle.draw(100, 10, 10)
  25. green_circle.draw(200, 20, 20)