forked from CatalinStefan/python-design-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemento.py
More file actions
52 lines (34 loc) · 1.27 KB
/
Copy pathmemento.py
File metadata and controls
52 lines (34 loc) · 1.27 KB
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
from dataclasses import dataclass
@dataclass
class Memento:
state: str
class Originator:
def __init__(self, state):
self.state = state
def create_memento(self):
return Memento(self.state)
def restore_memento(self, memento: Memento):
self.state = memento.state
class Caretaker:
memento_list = []
def save_state(self, state: Memento):
self.memento_list.append(state)
def restore(self, index: int):
return self.memento_list[index]
if __name__ == '__main__':
originator = Originator("initial state")
caretaker = Caretaker()
caretaker.save_state(originator.create_memento())
print(f"Current state is {originator.state}")
originator.state = "state 1"
caretaker.save_state(originator.create_memento())
print(f"Current state is {originator.state}")
originator.state = "state 2"
caretaker.save_state(originator.create_memento())
print(f"Current state is {originator.state}")
originator.restore_memento(caretaker.restore(1))
print(f"Current state is {originator.state}")
originator.restore_memento(caretaker.restore(0))
print(f"Current state is {originator.state}")
originator.restore_memento(caretaker.restore(2))
print(f"Current state is {originator.state}")