-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathcommand.cr
95 lines (77 loc) · 1.44 KB
/
command.cr
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
# The command pattern is a design pattern that enables all of the
# information for a request to be contained within a single object.
# The command can then be invoked as required, often as part of a
# batch of queued commands with rollback capabilities.
abstract class Command
abstract def execute
abstract def undo
end
class MoveLeft < Command
def execute
puts "One step left"
end
def undo
puts "Undo step left"
end
end
class MoveRight < Command
def execute
puts "One step right"
end
def undo
puts "Undo step right"
end
end
class Hit < Command
def execute
puts "Do one hit"
end
def undo
puts "Undo one hit"
end
end
class CommandSequence < Command
def initialize
@commands = [] of Command
end
def <<(command)
@commands << command
end
def execute
@commands.each &.execute
end
def undo
@commands.reverse.each &.undo
end
end
class CommandSequencePlayer
def initialize(@sequence : CommandSequence)
end
def forward
@sequence.execute
end
def backward
@sequence.undo
end
end
# Sample
sequence = CommandSequence.new.tap do |r|
r << MoveLeft.new
r << MoveLeft.new
r << MoveLeft.new
r << Hit.new
r << MoveRight.new
end
player = CommandSequencePlayer.new sequence
player.forward
# One step left
# One step left
# One step left
# Do one hit
# One step right
player.backward
# Undo step right
# Undo one hit
# Undo step left
# Undo step left
# Undo step left