This repository has been archived by the owner on Jan 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 32
/
memento.py
67 lines (48 loc) · 1.69 KB
/
memento.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
"""Memento pattern
"""
class Originator(object):
"""Originator is some object that has an internal state.
The Originator knows how to save and restore itself, but it's the Caretaker
than controls when to save and restore the Originator."""
def __init__(self):
self._state = None
@property
def state(self):
return self._state
@state.setter
def state(self, new_state):
self._state = new_state
def save(self):
"""Create a Memento and copy the Originator state in it."""
return Memento(self.state)
def restore(self, memento):
"""Restore the Originator to a previous state (stored in Memento)."""
self.state = memento.state
class Memento(object):
"""Memento is an opaque object that holds the state of an Originator."""
def __init__(self, state):
self._state = state
@property
def state(self):
return self._state
# Client, the Caretaker of the Memento pattern.
# The Caretaker is going to do something to the Originator, but wants to be
# able to undo the change.
# The Caretaker holds the Memento but cannot change it (Memento is opaque).
# The Caretaker knows when to save and when to restore the Originator.
def main():
originator = Originator()
originator.state = "State1"
memento1 = originator.save()
originator.state = "State2"
memento2 = originator.save()
originator.state = "State3"
originator.state = "State4"
originator.restore(memento1)
assert originator.state == "State1"
print(originator.state)
originator.restore(memento2)
assert originator.state == "State2"
print(originator.state)
if __name__ == "__main__":
main()