template.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
  2. An example of the Template pattern in Python"""
  3. ingredients = "spam eggs apple"
  4. line = '-' * 10
  5. # Skeletons
  6. def iter_elements(getter, action):
  7. """Template skeleton that iterates items"""
  8. for element in getter():
  9. action(element)
  10. print(line)
  11. def rev_elements(getter, action):
  12. """Template skeleton that iterates items in reverse order"""
  13. for element in getter()[::-1]:
  14. action(element)
  15. print(line)
  16. # Getters
  17. def get_list():
  18. return ingredients.split()
  19. def get_lists():
  20. return [list(x) for x in ingredients.split()]
  21. # Actions
  22. def print_item(item):
  23. print(item)
  24. def reverse_item(item):
  25. print(item[::-1])
  26. # Makes templates
  27. def make_template(skeleton, getter, action):
  28. """Instantiate a template method with getter and action"""
  29. def template():
  30. skeleton(getter, action)
  31. return template
  32. # Create our template functions
  33. templates = [make_template(s, g, a)
  34. for g in (get_list, get_lists)
  35. for a in (print_item, reverse_item)
  36. for s in (iter_elements, rev_elements)]
  37. # Execute them
  38. for template in templates:
  39. template()