-
Notifications
You must be signed in to change notification settings - Fork 12
/
observer.cr
75 lines (58 loc) · 1.41 KB
/
observer.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
# Defines a link between objects so that when one object's state
# changes, all dependent objects are update automatically. Allows
# communication between objects in a loosely coupled manner.
abstract class Observer
abstract def update(fighter)
end
module Observable(T)
getter observers
def add_observer(observer : Observer)
@observers ||= [] of T
@observers.not_nil! << observer
end
def delete_observer(observer)
@observers.try &.delete(observer)
end
def notify_observers
@observers.try &.each &.update self
end
end
class Fighter
include Observable(Observer)
getter name, health
def initialize(@name : String)
@health = 100
end
def damage(rate : Int32)
if @health > rate
@health -= rate
else
@health = 0
end
notify_observers
end
def dead?
@health <= 0
end
end
class Stats < Observer
def update(fighter)
puts "Updating stats: #{fighter.name}'s health is #{fighter.health}"
end
end
class DieAction < Observer
def update(fighter)
puts "#{fighter.name} is dead. Fight is over!" if fighter.dead?
end
end
# Sample
fighter = Fighter.new("Scorpion")
fighter.add_observer(Stats.new)
fighter.add_observer(DieAction.new)
fighter.damage(10)
# Updating stats: Scorpion's health is 90
fighter.damage(30)
# Updating stats: Scorpion's health is 60
fighter.damage(75)
# Updating stats: Scorpion's health is 0
# Scorpion is dead. Fight is over!