forked from piscolomo/ruby-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactory.rb
47 lines (39 loc) · 741 Bytes
/
factory.rb
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
# Define an interface for creating an object, but let subclasses decide which
# class to instantiate
class Party
attr_reader :members
def initialize(factory)
@members = []
@factory = factory
end
def add_warriors(n)
n.times{ @members << @factory.create_warrior }
end
def add_mages(n)
n.times{ @members << @factory.create_mage }
end
end
class HeroFactory
def create_warrior
Warrior.new
end
def create_mage
Mage.new
end
end
class Hero
def initialize
end
end
class Warrior < Hero
end
class Mage < Hero
end
# Usage
party = Party.new(HeroFactory.new)
party.add_warriors(3)
party.add_mages(2)
puts party.members.size
# => 5
puts party.members.count{ |member| member.class == "Mage" }
# => 2