定義可資生成物件的介面,但讓子類別去決定該具現出哪一種類別的物件。此模式讓類別將具現化程序交付給子類別去處置。
先從單純的架構來說明工廠方法的使用
class Transportation
def factory_method
raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"
end
def transport
tool = factory_method
result = "Transportation: The same creator's code has just worked with #{tool.operation}"
result
end
end
class LandTransport < Transportation
def factory_method
Truck.new
end
end
class Tools
def operation
raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"
end
end
class Truck < Tools
def operation
'{Result of the Truck}'
end
end
def client_code(creator)
print "Client: I'm not aware of the creator's class, but it still works.\n"\
"#{creator.transport}"
end
puts 'App: Launched with the LandTransport.'
client_code(LandTransport.new)
App: Launched with the LandTransport.
Client: I'm not aware of the creator's class, but it still works.
Transportation: The same creator's code has just worked with {Result of the Truck}
transport
方法,但因為LandTransport
並不含此方法,經由繼承找到Transportation
內self
是LandTransport.new
tool = factory_method
實際樣子為tool = LandTransport.new.factory_method
LandTransport
類別內的factory_method
會實體化Truck
Truck
呼叫operation
,獲得結果首先工廠方法模式(Factory Method)是產生物件,而產生物件的方法則為factory_method
,在這裡的物件指的是Truck.new
其實這裡的概念用白話文解釋是,當我輸入陸運,就會得到貨車的交通工具。而這部分只是在說明為什麼稱之為**工廠方法模式(Factory Method)**而已,並還沒有展現優勢
如果今天要增設海運該怎麼解決這問題呢? 或許可以使用一個交通類別,去給各個運輸繼承。
但這會造成交通類別內需要寫入判斷式來決定該執行海運類別還是陸運類別,而我們之前討論過,若是判斷式出現時,應該要思考到增設介面才是。
而有幾個時機是適合使用工廠方法模式(Factory Method)
factory_method
而生成貨車實體... 待續