Skip to content

Commit ecf9a24

Browse files
Strategy Patterns
1 parent 893fcfd commit ecf9a24

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
from abc import ABC
2+
from enum import Enum, auto
3+
4+
5+
class OutputFormat(Enum):
6+
MARKDOWN = auto()
7+
HTML = auto()
8+
9+
10+
# not required but a good idea
11+
class ListStrategy(ABC):
12+
def start(self, buffer): pass
13+
14+
def end(self, buffer): pass
15+
16+
def add_list_item(self, buffer, item): pass
17+
18+
19+
class MarkdownListStrategy(ListStrategy):
20+
21+
def add_list_item(self, buffer, item):
22+
buffer.append(f' * {item}\n')
23+
24+
25+
class HtmlListStrategy(ListStrategy):
26+
27+
def start(self, buffer):
28+
buffer.append('<ul>\n')
29+
30+
def end(self, buffer):
31+
buffer.append('</ul>\n')
32+
33+
def add_list_item(self, buffer, item):
34+
buffer.append(f' <li>{item}</li>\n')
35+
36+
37+
class TextProcessor:
38+
def __init__(self, list_strategy=HtmlListStrategy()):
39+
self.buffer = []
40+
self.list_strategy = list_strategy
41+
42+
def append_list(self, items):
43+
self.list_strategy.start(self.buffer)
44+
for item in items:
45+
self.list_strategy.add_list_item(
46+
self.buffer, item
47+
)
48+
self.list_strategy.end(self.buffer)
49+
50+
def set_output_format(self, format):
51+
if format == OutputFormat.MARKDOWN:
52+
self.list_strategy = MarkdownListStrategy()
53+
elif format == OutputFormat.HTML:
54+
self.list_strategy = HtmlListStrategy()
55+
56+
def clear(self):
57+
self.buffer.clear()
58+
59+
def __str__(self):
60+
return ''.join(self.buffer)
61+
62+
63+
if __name__ == '__main__':
64+
items = ['foo', 'bar', 'baz']
65+
66+
tp = TextProcessor()
67+
tp.set_output_format(OutputFormat.MARKDOWN)
68+
tp.append_list(items)
69+
print(tp)
70+
71+
tp.set_output_format(OutputFormat.HTML)
72+
tp.clear()
73+
tp.append_list(items)
74+
print(tp)

0 commit comments

Comments
 (0)