-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy path11_factory_method_sample2.rb
More file actions
69 lines (59 loc) Β· 1.57 KB
/
11_factory_method_sample2.rb
File metadata and controls
69 lines (59 loc) Β· 1.57 KB
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
# -*- coding: utf-8 -*-
# γ΅γγ―γΉ (Product)
class Saxophone
def initialize(name)
@name = name
end
def play
puts "γ΅γγ―γΉ #{@name} γ―ι³γε₯γ§γ¦γγΎγ"
end
end
# γγ©γ³γγγ (Product)
class Trumpet
def initialize(name)
@name = name
end
def play
puts "γγ©γ³γγγ #{@name} γ―ι³γε₯γ§γ¦γγΎγ"
end
end
# ζ₯½ε¨ε·₯ε ΄ (Creator)
class InstrumentFactory
def initialize(number_instruments)
@instruments = []
number_instruments.times do |i|
instrument = new_instrument("ζ₯½ε¨ #{i}")
@instruments << instrument
end
end
# ζ₯½ε¨γεΊθ·γγ
def ship_out
tmp = @instruments.dup
@instruments = []
tmp
end
end
# SaxophoneFactory: γ΅γγ―γΉγηζγγ (ConcreteCreator)
class SaxophoneFactory < InstrumentFactory
def new_instrument(name)
Saxophone.new(name)
end
end
# TrumpetFactory: γγ©γ³γγγγηζγγ (ConcreteCreator)
class TrumpetFactory < InstrumentFactory
def new_instrument(name)
Trumpet.new(name)
end
end
# ===========================================
factory = SaxophoneFactory.new(3)
saxophones = factory.ship_out
saxophones.each { |saxophone| saxophone.play }
#=> γ΅γγ―γΉ ζ₯½ε¨ 0 γ―ι³γε₯γ§γ¦γγΎγ
#=> γ΅γγ―γΉ ζ₯½ε¨ 1 γ―ι³γε₯γ§γ¦γγΎγ
#=> γ΅γγ―γΉ ζ₯½ε¨ 2 γ―ι³γε₯γ§γ¦γγΎγ
factory = TrumpetFactory.new(2)
trumpets = factory.ship_out
trumpets.each { |trumpet| trumpet.play }
#=> γγ©γ³γγγ ζ₯½ε¨ 0 γ―ι³γε₯γ§γ¦γγΎγ
#=> γγ©γ³γγγ ζ₯½ε¨ 1 γ―ι³γε₯γ§γ¦γγΎγ