Skip to content

Commit 973c209

Browse files
committed
add Memento pattern
1 parent d68bc3b commit 973c209

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

memento/Memento.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#
2+
# Python Design Patterns: Memento
3+
# Author: Jakub Vojvoda [github.com/JakubVojvoda]
4+
# 2016
5+
#
6+
# Source code is licensed under MIT License
7+
# (for more details see LICENSE)
8+
#
9+
10+
import sys
11+
12+
#
13+
# Memento
14+
# stores internal state of the Originator object and protects
15+
# against access by objects other than the originator
16+
#
17+
class Memento:
18+
def __init__(self, state):
19+
self._state = state
20+
21+
def setState(self, state):
22+
self._state = state;
23+
24+
def getState(self):
25+
return self._state
26+
27+
#
28+
# Originator
29+
# creates a memento containing a snapshot of its current internal
30+
# state and uses the memento to restore its internal state
31+
#
32+
class Originator:
33+
def __init__(self):
34+
self._state = 0
35+
36+
def setState(self, state):
37+
print("Set state to " + str(state) + ".")
38+
self._state = state
39+
40+
def getState(self):
41+
return self._state
42+
43+
def setMemento(self, memento):
44+
self._state = memento.getState()
45+
46+
def createMemento(self):
47+
return Memento(self._state)
48+
49+
#
50+
# CareTaker
51+
# is responsible for the memento's safe keeping
52+
#
53+
class CareTaker:
54+
def __init__(self, originator):
55+
self._originator = originator
56+
self._history = []
57+
58+
def save(self):
59+
print("Save state.")
60+
self._history.append(self._originator.createMemento())
61+
62+
def undo(self):
63+
print("Undo state.")
64+
self._originator.setMemento(self._history[-1])
65+
self._history.pop()
66+
67+
68+
if __name__ == "__main__":
69+
originator = Originator()
70+
caretaker = CareTaker(originator)
71+
72+
originator.setState(1)
73+
caretaker.save()
74+
75+
originator.setState(2)
76+
caretaker.save()
77+
78+
originator.setState(3)
79+
caretaker.undo()
80+
81+
print("Actual state is " + str(originator.getState()) + ".")

0 commit comments

Comments
 (0)