-
Notifications
You must be signed in to change notification settings - Fork 12
/
composite.cr
62 lines (50 loc) · 1001 Bytes
/
composite.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
# The composite pattern is a design pattern that is used when
# creating hierarchical object models. The pattern defines a
# manner in which to design recursive tree structures of objects,
# where individual objects and groups can be accessed in the same manner
abstract class Strike
abstract def damage
abstract def attack
end
class Punch < Strike
def attack
puts "Hitting with punch"
end
def damage
5
end
end
class Kick < Strike
def attack
puts "Hitting with kick"
end
def damage
8
end
end
class Combo < Strike
def initialize
@sub_strikes = [] of Strike
end
def <<(strike)
@sub_strikes << strike
end
def damage
@sub_strikes.reduce(0) { |acc, x| acc + x.damage }
end
def attack
@sub_strikes.each &.attack
end
end
# Sample
super_strike = Combo.new.tap do |s|
s << Kick.new
s << Kick.new
s << Punch.new
end
super_strike.attack
# Hitting with kick
# Hitting with kick
# Hitting with punch
super_strike.damage
# => 21