-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path03-factory-method.rb
68 lines (56 loc) · 1.33 KB
/
03-factory-method.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# 03. FACTORY METHOD
# Creator
class VehicleFactory
def create(options)
type = options.fetch(:type)
color = options.fetch(:color)
if type == 'car'
Car.new(color)
elsif type == 'motorbike'
Motorbike.new(color)
else
raise ArgumentError.new("The type #{ type } is not valid")
end
end
end
# Concrete creator
class BlueVehicleFactory < VehicleFactory
def create(options)
# This factory only creates blue vehicles
super(options.merge(color: 'blue'))
end
end
# Product
class Vehicle
attr_reader :color
def initialize(color)
@color = color
end
end
# Concrete products
class Car < Vehicle
def to_s
"I'm a #{ self.color } car"
end
end
class Motorbike < Vehicle
def to_s
"I'm a #{ self.color } motorbike"
end
end
# Client using the Creator
factory = VehicleFactory.new
blue_car = factory.create(type: 'car', color: 'blue')
pink_car = factory.create(type: 'car', color: 'pink')
pink_motorbike = factory.create(type: 'motorbike', color: 'pink')
puts blue_car
puts pink_car
puts pink_motorbike
# Client using a Contrete creator
factory = BlueVehicleFactory.new
blue_car = factory.create(type: 'car', color: 'blue')
pink_car = factory.create(type: 'car', color: 'pink')
pink_motorbike = factory.create(type: 'motorbike', color: 'pink')
puts blue_car
puts pink_car
puts pink_motorbike