Design pattern學習 – 5 (Factory工廠模式)

目的:

提供一個工廠介面,將產生實體的程式碼交由子類別各自實現。

備註:

簡單工廠模式工廠模式比較:

簡單工廠模式的工廠直接負責所有產品的生產工作,利用if else或switch case來判斷生產哪一個產品。

工廠模式下的工廠提升為一個概念,實際上管理產品生產工作的是實作工廠概念的實體工廠。

Swift sample code:

// Product and Concrete Product
protocol Adventurer {
func getType() -> String
}
class Archer: Adventurer {
func getType() -> String {
print("I'm an archer")
return String(describing: Archer.self)
}
}
class Warrior: Adventurer {
func getType() -> String {
print("I'm a warrior")
return String(describing: Warrior.self)
}
}
// Factory and Concrete Factory
protocol TrainingCamp {
func trainAdventurer() -> Adventurer
}
class ArcherTrainingCamp: TrainingCamp {
func trainAdventurer() -> Adventurer {
print("Train an archer")
return Archer()
}
}
class WarriorTrainingCamp: TrainingCamp {
func trainAdventurer() -> Adventurer {
print("Train an warrior")
return Warrior()
}
}
let archer = ArcherTrainingCamp().trainAdventurer()
let warrior = WarriorTrainingCamp().trainAdventurer()
// Testing code
assert(archer is Archer, "Didn't get the archer object!!")
assert(warrior is Warrior, "Didn't get the warrior object!!")
view raw gistfile1.txt hosted with ❤ by GitHub
%d 位部落客按了讚: