-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathCommandExample.rb
132 lines (123 loc) · 2.42 KB
/
CommandExample.rb
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
require 'singleton'
class Command
def execute()
end
def unexecute()
end
end
class Buffer
include Singleton
@buffer = []
def initialize()
@buffer = []
end
def insert(n, token)
@buffer.insert( n, token )
end
def string()
return @buffer.join( " " )
end
def remove(n)
val = @buffer[n]
@buffer.delete_at(n)
return val
end
end
class PasteCommand < Command
def initialize(n, token)
@n = n
@token = token
end
def execute()
Buffer.instance.insert(@n, @token)
end
def unexecute()
Buffer.instance.remove(@n)
end
end
class RemoveCommand < Command
@token = nil
def initialize(n)
@n = n
end
def execute()
@token = Buffer.instance.remove(@n)
end
def unexecute()
Buffer.instance.insert(@n, @token)
end
end
def example_driver()
puts(Buffer.instance.string())
actions = [
PasteCommand.new(0,"Hello"),
PasteCommand.new(1,"World"),
PasteCommand.new(1,"Beautiful"),
RemoveCommand.new(2),
RemoveCommand.new(0),
]
for action in actions
action.execute()
puts(Buffer.instance.string())
end
revactions = actions.reverse
for action in revactions
action.unexecute()
puts(Buffer.instance.string())
end
end
example_driver()
class Invoker
def initialize()
@undoqueue = []
@redoqueue = []
end
def do(x)
x.execute()
@undoqueue << x
@redoqueue = []
end
def undo()
x = @undoqueue.pop()
x.unexecute() if x
@redoqueue << x if x
end
def redo()
x = @redoqueue.pop()
if (x)
x.execute()
@undoqueue << x
end
end
end
class BufferInvoker < Invoker
def do(x)
super(x)
puts(Buffer.instance.string())
end
def undo()
super()
puts(Buffer.instance.string())
end
def redo()
super()
puts(Buffer.instance.string())
end
end
def example_invoker()
invoker = BufferInvoker.new()
[
PasteCommand.new(0,"Snakes"),
PasteCommand.new(1,"Hiss"),
PasteCommand.new(1,"Go"),
RemoveCommand.new(2),
RemoveCommand.new(0),
].each { |x| invoker.do( x ) }
for i in (1..5)
invoker.undo()
end
for i in (1..5)
invoker.redo()
end
end
example_invoker()