abstract_factory.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. # 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. shop = PetShop()
  46. for i in range(3):
  47. shop.pet_factory = get_factory()
  48. shop.show_pet()
  49. print("=" * 20)