bridge.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Bridge_Pattern#Python
  2. # ConcreteImplementor 1/2
  3. class DrawingAPI1:
  4. def drawCircle(self, x, y, radius):
  5. print('API1.circle at {}:{} radius {}'.format(x, y, radius))
  6. # ConcreteImplementor 2/2
  7. class DrawingAPI2:
  8. def drawCircle(self, x, y, radius):
  9. print('API2.circle at {}:{} radius {}'.format(x, y, radius))
  10. # Refined Abstraction
  11. class CircleShape:
  12. def __init__(self, x, y, radius, drawingAPI):
  13. self.__x = x
  14. self.__y = y
  15. self.__radius = radius
  16. self.__drawingAPI = drawingAPI
  17. # low-level i.e. Implementation specific
  18. def draw(self):
  19. self.__drawingAPI.drawCircle(self.__x, self.__y, self.__radius)
  20. # high-level i.e. Abstraction specific
  21. def resizeByPercentage(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.resizeByPercentage(2.5)
  30. shape.draw()
  31. if __name__ == "__main__":
  32. main()