forked from ls1248659692/python_guide
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.py
More file actions
38 lines (27 loc) · 786 Bytes
/
command.py
File metadata and controls
38 lines (27 loc) · 786 Bytes
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
from collections import deque
class Document(object):
value = ""
cmd_stack = deque()
@classmethod
def execute(cls, cmd):
cmd.redo()
cls.cmd_stack.append(cmd)
@classmethod
def undo(cls):
cmd = cls.cmd_stack.pop()
cmd.undo()
class AddTextCommand(object):
def __init__(self, text):
self.text = text
def redo(self):
Document.value += self.text
def undo(self):
Document.value = Document.value[:-len(self.text)]
if __name__ == '__main__':
cmds = [AddTextCommand("liu"), AddTextCommand("xin"), AddTextCommand("heihei")]
for cmd in cmds:
Document.execute(cmd)
print(Document.value)
for i in range(len(cmds)):
Document.undo()
print(Document.value)