-
Notifications
You must be signed in to change notification settings - Fork 12
/
decorator.cr
84 lines (67 loc) · 1.66 KB
/
decorator.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
# Defines a manner for creating relationships between classes or entities.
# The decorator pattern is used to extend or alter the functionality of objects
# at run-time by wrapping them in an object of a decorator class.
# This provides a flexible alternative to using inheritance to modify behaviour.
abstract class Fighter
abstract def power
abstract def abilities
end
class Scorpion < Fighter
def power
25.0
end
def abilities
%w(hellfire shuriken)
end
end
class FighterAbility < Fighter
getter fighter : Fighter
def initialize(@fighter)
end
def power
fighter.power
end
def abilities
fighter.abilities
end
end
class Spear < FighterAbility
def power
super + 10
end
def abilities
super << "spear"
end
end
class LegTakedown < FighterAbility
def power
super + 15
end
def abilities
super << "leg takedown"
end
end
class FireBall < FighterAbility
def power
super + 25
end
def abilities
super << "fire ball"
end
end
scorpion = Scorpion.new
pp scorpion.power, scorpion.abilities
# scorpion.power # => 25.0
# scorpion.abilities # => ["hellfire", "shuriken"]
scorpion = Spear.new(scorpion)
pp scorpion.power, scorpion.abilities
# scorpion.power # => 35.0
# scorpion.abilities # => ["hellfire", "shuriken", "spear"]
scorpion = LegTakedown.new(scorpion)
pp scorpion.power, scorpion.abilities
# scorpion.power # => 50.0
# scorpion.abilities # => ["hellfire", "shuriken", "spear", "leg takedown"]
scorpion = FireBall.new(scorpion)
pp scorpion.power, scorpion.abilities
# scorpion.power # => 75.0
# scorpion.abilities # => ["hellfire", "shuriken", "spear", "leg takedown", "fire ball"]