Design pattern學習 – 4 (Simple Factory簡單工廠模式)

目的:

定義一個簡單工廠,傳入不同的參數取得不同的類別物件。

備註:

Simple Factory其實違反了SOLID中的open/close principle,因為每次想要擴充可產生的object種類,都要ㄧ再修改Simple Factory中負責產生object的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)
}
}
// Simple Factory
class TrainingCamp {
static func trainAdventurer(type: String) -> Adventurer? {
switch type {
case "archer":
return Archer()
case "warrior":
return Warrior()
default:
return nil
}
}
}
let archer = TrainingCamp.trainAdventurer(type: "archer")
let warrior = TrainingCamp.trainAdventurer(type: "warrior")
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