abstract_factory.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. class CatFactory:
  33. def get_pet(self):
  34. return Cat()
  35. # Create the proper family
  36. def get_factory():
  37. """Let's be dynamic!"""
  38. return random.choice([DogFactory, CatFactory])()
  39. # Show pets with various factories
  40. if __name__ == "__main__":
  41. for i in range(3):
  42. shop = PetShop(get_factory())
  43. shop.show_pet()
  44. print("=" * 20)
  45. ### OUTPUT ###
  46. # We have a lovely Dog
  47. # It says woof
  48. # We also have dog food
  49. # ====================
  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. # ====================