template.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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()
  40. ### OUTPUT ###
  41. # spam
  42. # ----------
  43. # eggs
  44. # ----------
  45. # apple
  46. # ----------
  47. # apple
  48. # ----------
  49. # eggs
  50. # ----------
  51. # spam
  52. # ----------
  53. # maps
  54. # ----------
  55. # sgge
  56. # ----------
  57. # elppa
  58. # ----------
  59. # elppa
  60. # ----------
  61. # sgge
  62. # ----------
  63. # maps
  64. # ----------
  65. # ['s', 'p', 'a', 'm']
  66. # ----------
  67. # ['e', 'g', 'g', 's']
  68. # ----------
  69. # ['a', 'p', 'p', 'l', 'e']
  70. # ----------
  71. # ['a', 'p', 'p', 'l', 'e']
  72. # ----------
  73. # ['e', 'g', 'g', 's']
  74. # ----------
  75. # ['s', 'p', 'a', 'm']
  76. # ----------
  77. # ['m', 'a', 'p', 's']
  78. # ----------
  79. # ['s', 'g', 'g', 'e']
  80. # ----------
  81. # ['e', 'l', 'p', 'p', 'a']
  82. # ----------
  83. # ['e', 'l', 'p', 'p', 'a']
  84. # ----------
  85. # ['s', 'g', 'g', 'e']
  86. # ----------
  87. # ['m', 'a', 'p', 's']
  88. # ----------