bridge.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Bridge_Pattern#Python
  2. # ConcreteImplementor 1/2
  3. class DrawingAPI1(object):
  4. def draw_circle(self, x, y, radius):
  5. print('API1.circle at {}:{} radius {}'.format(x, y, radius))
  6. # ConcreteImplementor 2/2
  7. class DrawingAPI2(object):
  8. def draw_circle(self, x, y, radius):
  9. print('API2.circle at {}:{} radius {}'.format(x, y, radius))
  10. # Refined Abstraction
  11. class CircleShape(object):
  12. def __init__(self, x, y, radius, drawing_api):
  13. self._x = x
  14. self._y = y
  15. self._radius = radius
  16. self._drawing_api = drawing_api
  17. # low-level i.e. Implementation specific
  18. def draw(self):
  19. self._drawing_api.draw_circle(self._x, self._y, self._radius)
  20. # high-level i.e. Abstraction specific
  21. def scale(self, pct):
  22. self._radius *= pct
  23. def main():
  24. shapes = (
  25. CircleShape(1, 2, 3, DrawingAPI1()),
  26. CircleShape(5, 7, 11, DrawingAPI2())
  27. )
  28. for shape in shapes:
  29. shape.scale(2.5)
  30. shape.draw()
  31. if __name__ == '__main__':
  32. main()