abstract_factory.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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.
  10. We can set it at will."""
  11. self.pet_factory = animal_factory
  12. def show_pet(self):
  13. """Creates and shows a pet using the
  14. abstract factory"""
  15. pet = self.pet_factory.get_pet()
  16. print("This is a lovely {}".format(pet))
  17. print("It says {}".format(pet.speak()))
  18. print("It eats {}".format(self.pet_factory.get_food()))
  19. # Stuff that our factory makes
  20. class Dog:
  21. def speak(self):
  22. return "woof"
  23. def __str__(self):
  24. return "Dog"
  25. class Cat:
  26. def speak(self):
  27. return "meow"
  28. def __str__(self):
  29. return "Cat"
  30. # Factory classes
  31. class DogFactory:
  32. def get_pet(self):
  33. return Dog()
  34. def get_food(self):
  35. return "dog food"
  36. class CatFactory:
  37. def get_pet(self):
  38. return Cat()
  39. def get_food(self):
  40. return "cat food"
  41. # Create the proper family
  42. def get_factory():
  43. """Let's be dynamic!"""
  44. return random.choice([DogFactory, CatFactory])()
  45. # Show pets with various factories
  46. if __name__ == "__main__":
  47. shop = PetShop()
  48. for i in range(3):
  49. shop.pet_factory = get_factory()
  50. shop.show_pet()
  51. print("=" * 20)