forked from tuvo1106/python_design_patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrategy.py
More file actions
89 lines (62 loc) · 2.09 KB
/
strategy.py
File metadata and controls
89 lines (62 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""
Strategy
- Enables the exact behavior of a system to be selected at run-time
Motivation
- Many algorithms can be decomposed into higher and lower level parts
- Making tea can be decomposed into
- The process of making a hot beverage (boil water, pour into cup); and
- Tea-specific things (put teabag into water)
- The high-level algorithm can then be reused for making coffee or hot
chocolate
- Supported by beverage-specific strategies
"""
from abc import ABC
from enum import Enum, auto
class OutputFormat(Enum):
MARKDOWN = auto()
HTML = auto()
# not required but a good idea
class ListStrategy(ABC):
def start(self, buffer): pass
def end(self, buffer): pass
def add_list_item(self, buffer, item): pass
class MarkdownListStrategy(ListStrategy):
def add_list_item(self, buffer, item):
buffer.append(f' * {item}\n')
class HtmlListStrategy(ListStrategy):
def start(self, buffer):
buffer.append('<ul>\n')
def end(self, buffer):
buffer.append('</ul>\n')
def add_list_item(self, buffer, item):
buffer.append(f' <li>{item}</li>\n')
class TextProcessor:
def __init__(self, list_strategy=HtmlListStrategy()):
self.buffer = []
self.list_strategy = list_strategy
def append_list(self, items):
self.list_strategy.start(self.buffer)
for item in items:
self.list_strategy.add_list_item(
self.buffer, item
)
self.list_strategy.end(self.buffer)
def set_output_format(self, format):
if format == OutputFormat.MARKDOWN:
self.list_strategy = MarkdownListStrategy()
elif format == OutputFormat.HTML:
self.list_strategy = HtmlListStrategy()
def clear(self):
self.buffer.clear()
def __str__(self):
return ''.join(self.buffer)
if __name__ == '__main__':
items = ['foo', 'bar', 'baz']
TP = TextProcessor()
TP.set_output_format(OutputFormat.MARKDOWN)
TP.append_list(items)
print(TP)
TP.set_output_format(OutputFormat.HTML)
TP.clear()
TP.append_list(items)
print(TP)