-
-
Notifications
You must be signed in to change notification settings - Fork 127
/
Copy pathmemento_concept.py
89 lines (66 loc) · 2.19 KB
/
memento_concept.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
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
"Memento pattern concept"
class Memento(): # pylint: disable=too-few-public-methods
"A container of state"
def __init__(self, state):
self.state = state
class Originator():
"The Object in the application whose state changes"
def __init__(self):
self._state = ""
@property
def state(self):
"A `getter` for the objects state"
return self._state
@state.setter
def state(self, state):
print(f"Originator: Setting state to `{state}`")
self._state = state
@property
def memento(self):
"A `getter` for the objects state but packaged as a Memento"
print("Originator: Providing Memento of state to caretaker.")
return Memento(self._state)
@memento.setter
def memento(self, memento):
self._state = memento.state
print(
f"Originator: State after restoring from Memento: "
f"`{self._state}`")
class CareTaker():
"Guardian. Provides a narrow interface to the mementos"
def __init__(self, originator):
self._originator = originator
self._mementos = []
def create(self):
"Store a new Memento of the Originators current state"
print("CareTaker: Getting a copy of Originators current state")
memento = self._originator.memento
self._mementos.append(memento)
def restore(self, index):
"""
Replace the Originators current state with the state
stored in the saved Memento
"""
print("CareTaker: Restoring Originators state from Memento")
memento = self._mementos[index]
self._originator.memento = memento
# The Client
ORIGINATOR = Originator()
CARETAKER = CareTaker(ORIGINATOR)
# originators state can change periodically due to application events
ORIGINATOR.state = "State #1"
ORIGINATOR.state = "State #2"
# lets backup the originators
CARETAKER.create()
# more changes, and then another backup
ORIGINATOR.state = "State #3"
CARETAKER.create()
# more changes
ORIGINATOR.state = "State #4"
print(ORIGINATOR.state)
# restore from first backup
CARETAKER.restore(0)
print(ORIGINATOR.state)
# restore from second backup
CARETAKER.restore(1)
print(ORIGINATOR.state)