-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path17_strategy.py
44 lines (29 loc) · 838 Bytes
/
17_strategy.py
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
"""
Strategy
- a behavioral design pattern that lets you define a family of algorithms,
put each of them into a separate class, and make their objects interchangeable.
"""
import abc
class Read: # Context
def __init__(self, sentence):
self.sentence = sentence
self._direction = None # strategy instance
def set_direction(self, direction): # set_strategy
self._direction = direction
def read(self):
return self._direction.direct(self.sentence)
class Direction(abc.ABC): # Abstract Strategy
@abc.abstractmethod
def direct(self, data):
pass
class Right(Direction): # Concrete Strategy
def direct(self, data):
print(data[::-1])
class Left(Direction): # Concrete Strategy
def direct(self, data):
print(data[::1])
c = Read('Hello world')
c.set_direction(Right())
c.read()
c.set_direction(Left())
c.read()