abstract_factory.py 1.7 KB

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