/*
厂商现在有阿司匹林和扑热息痛生产线。
现在厂商想生产1mg*10s装、1mg*20s装的阿司匹林和扑热息痛。
*/
// 抽象產品
protocol MedicineProduct {
func getProduct(p_stName: String, p_stFormula: String) -> String
}
// 產品 1mg*10s装
class OneMgTenProduct : MedicineProduct {
func getProduct(p_stName: String, p_stFormula: String) -> String {
return "\(p_stName) 1mg*10s, Formula: \(p_stFormula)"
}
}
// 產品 1mg*20s装
class OneMgTwentyProduct : MedicineProduct {
func getProduct(p_stName: String, p_stFormula: String) -> String {
return "\(p_stName) 1mg*20s, Formula: \(p_stFormula)"
}
}
// 抽象工廠
protocol AbstractMedicineFactory {
func createProduct() -> MedicineProduct
}
// 工廠 1mg*10s装
class OneMgTenFactory : AbstractMedicineFactory {
static let sharedInstance: OneMgTenFactory = OneMgTenFactory()
func createProduct() -> MedicineProduct {
return OneMgTenProduct()
}
}
// 工廠 1mg*20s装
class OneMgTwentyFactory : AbstractMedicineFactory {
static let sharedInstance: OneMgTwentyFactory = OneMgTwentyFactory()
func createProduct() -> MedicineProduct {
return OneMgTwentyProduct()
}
}
let tenMgProduct: MedicineProduct = OneMgTenFactory.sharedInstance.createProduct()
let twentyMgProduct: MedicineProduct = OneMgTwentyFactory.sharedInstance.createProduct()
// 生產 1mg*10s装 藥物
print(tenMgProduct.getProduct(p_stName: "Aspirin", p_stFormula: "C9H8O4"))
print(tenMgProduct.getProduct(p_stName: "Paracetamol", p_stFormula: "C8H9NO2"))
// 生產 1mg*20s装 藥物
print(twentyMgProduct.getProduct(p_stName: "Aspirin", p_stFormula: "C9H8O4"))
print(twentyMgProduct.getProduct(p_stName: "Paracetamol", p_stFormula: "C8H9NO2"))
// 假如想增加1mg*30s装 生產線、只需增加工廠和產品
Swift 02 抽象工厂模式 Abstract Factory Pattern
最新推荐文章于 2024-08-23 14:00:37 发布