abstract_factory.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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("We have a lovely {}".format(pet))
  17. print("It says {}".format(pet.speak()))
  18. print("We also have {}".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)
  52. ### OUTPUT ###
  53. # We have a lovely Dog
  54. # It says woof
  55. # We also have dog food
  56. # ====================
  57. # We have a lovely Dog
  58. # It says woof
  59. # We also have dog food
  60. # ====================
  61. # We have a lovely Dog
  62. # It says woof
  63. # We also have dog food
  64. # ====================