abstract_factory.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
  4. """Implementation of the abstract factory pattern"""
  5. import random
  6. class PetShop:
  7. """A pet shop"""
  8. def __init__(self, animal_factory=None):
  9. """pet_factory is our abstract factory. We can set it at will."""
  10. self.pet_factory = animal_factory
  11. def show_pet(self):
  12. """Creates and shows a pet using the abstract factory"""
  13. pet = self.pet_factory.get_pet()
  14. print("We have a lovely {}".format(pet))
  15. print("It says {}".format(pet.speak()))
  16. print("We also have {}".format(self.pet_factory.get_food()))
  17. # Stuff that our factory makes
  18. class Dog:
  19. def speak(self):
  20. return "woof"
  21. def __str__(self):
  22. return "Dog"
  23. class Cat:
  24. def speak(self):
  25. return "meow"
  26. def __str__(self):
  27. return "Cat"
  28. # Factory classes
  29. class DogFactory:
  30. def get_pet(self):
  31. return Dog()
  32. def get_food(self):
  33. return "dog food"
  34. class CatFactory:
  35. def get_pet(self):
  36. return Cat()
  37. def get_food(self):
  38. return "cat food"
  39. # Create the proper family
  40. def get_factory():
  41. """Let's be dynamic!"""
  42. return random.choice([DogFactory, CatFactory])()
  43. # Show pets with various factories
  44. if __name__ == "__main__":
  45. for i in range(3):
  46. shop = PetShop(get_factory())
  47. shop.show_pet()
  48. print("=" * 20)
  49. ### OUTPUT ###
  50. # We have a lovely Dog
  51. # It says woof
  52. # We also have dog food
  53. # ====================
  54. # We have a lovely Dog
  55. # It says woof
  56. # We also have dog food
  57. # ====================
  58. # We have a lovely Cat
  59. # It says meow
  60. # We also have cat food
  61. # ====================