-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmemento.cr
58 lines (48 loc) · 1.57 KB
/
memento.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
# The memento pattern is a design pattern that permits the current state
# of an object to be stored without breaking the rules of encapsulation.
# The originating object can be modified as required but can be restored
# to the saved state at any time.
# The class whose state can be saved with a memento
class Match
def initialize(fighter1, fighter2, rounds, time)
@state = State.new({fighter1, fighter2}, rounds, time)
end
def save_memento
@state
end
def restore_memento(memento : Match::State)
@state = memento
end
def start
print "Starting fight between #{@state.fighters[0]} and #{@state.fighters[1]}!"
puts " (#{@state.rounds} rounds of #{@state.time.total_seconds} seconds)"
end
def rounds=(rounds)
@state.rounds = rounds
end
def fighters=(fighters)
@state.fighters = fighters
end
# The memento class. This is an opaque class for the client.
struct State
getter fighters, rounds, time
protected setter fighters, rounds, time
def initialize(
@fighters : Tuple(String, String),
@rounds : Int32,
@time : Time::Span)
end
end
end
match = Match.new("Liu Kang", "Kano", 3, 60.seconds)
# Save the current state
previous_match_state = match.save_memento
# Change the state
match.rounds = 5
match.fighters = {"Sonya Blade", "Goro"}
match.start
# Restore the previous state
match.restore_memento(previous_match_state)
match.start
# Starting fight between Sonya Blade and Goro! (5 rounds of 60.0 seconds)
# Starting fight between Liu Kang and Kano! (3 rounds of 60.0 seconds)