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