bridge.py 1.2 KB

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