-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.py
More file actions
70 lines (41 loc) · 1.36 KB
/
command.py
File metadata and controls
70 lines (41 loc) · 1.36 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from abc import ABC, abstractmethod
class Command(ABC):
@abstractmethod
def execute()-> None:
pass
@abstractmethod
def unexecute()-> None:
pass
class Document():
def __init__(self):
self.text = ""
def getText(self):
return self.text
def insertText(self, position, newtext):
orginal = self.text
self.text = orginal[ : position] + newtext + orginal[position : ]
def deleteText(self, position, textLength):
orginal = self.text
self.text = orginal[ : position] + orginal[position+textLength : ]
class PasteCommand(Command):
def __init__(self, document:Document, position:int, text:str):
self.document = document
self.text = text
self.position = position
def execute(self):
self.document.insertText(self.position, self.text)
def unexecute(self):
self.document.deleteText(self.position, len(self.text))
class Editor():
def invokePasteCommand(self, command:Command):
command.execute()
def invokeUndoPasteCommand(self, command:Command):
command.unexecute()
editor = Editor()
doc = Document()
doc.text = "the original text goes here"
pasteCommand = PasteCommand(doc, 0, "Hello World!")
editor.invokePasteCommand(pasteCommand)
print(doc.getText())
editor.invokeUndoPasteCommand(pasteCommand)
print(doc.getText())