基本概念
建造者模式主要用於分離物件的建立和配置。呼叫元件負責提供資料。並負責將配置資料傳遞給建造者。建造者代替呼叫元件去建立響應的物件。
好處
- 使修改物件的預設值變簡單
- 呼叫元件無需關心太多物件的構建過程
何時使用
- 物件建立需要進行復雜的配置。構造過程複雜。不想預設配置分散到程式的各個角落,此時可以使用建造者模式
示例程式
新建一個名為Builder的 OSX命令列程式
實現如下程式碼
///Food.swift
class Burger {
enum Cooked:String {
case rare = "Rare"
case normal = "Normal"
case wellDone = "Well Done"
}
let customerName:String
let veggieProduct:Bool
let patties:Int
let pickles:Bool
let mayo:Bool
let ketchup:Bool
let cook:Cooked
init(name:String,veggie:Bool,patties:Int,pickles:Bool,
mayo:Bool,ketchup:Bool,lettuce:Bool,cook:Cooked) {
self.customerName = name
self.veggieProduct = veggie
self.patties = patties
self.pickles = pickles
self.mayo = mayo
self.ketchup = ketchup
self.cook = cook
}
func printDescription() {
print("Name \(customerName)")
print("Vegie \(veggieProduct)")
print("Patties \(patties)")
print("Pickles \(pickles)")
print("Mayo \(mayo)")
print("Ketchup \(ketchup)")
print("Cook \(cook.rawValue)")
}
}
///BurgerBuilder.swift
final class BurgerBuilder {
private var veggie:Bool = false
private var pickles:Bool = false
private var mayo:Bool = true
private var ketchup:Bool = true
private var lettuce:Bool = true
private var cooked:Burger.Cooked = .normal
private var patties:Int = 2
func setVeggie(_ choice:Bool) -> BurgerBuilder{
veggie = choice
return self
}
func setPickles(_ choice:Bool) -> BurgerBuilder {
pickles = choice
return self
}
func setMayo(_ choice:Bool) -> BurgerBuilder {
mayo = choice
return self
}
func setKetchup(_ choice:Bool) -> BurgerBuilder {
ketchup = choice
return self
}
func setLettuce(_ choice:Bool) -> BurgerBuilder {
lettuce = choice
return self
}
func setCooked(_ choice:Burger.Cooked) -> BurgerBuilder {
cooked = choice
return self
}
func addPatty(_ choice:Bool) -> BurgerBuilder {
patties = choice ? 3 : 2
return self
}
func buildBurgerObject(name:String) -> Burger {
return Burger(name: name, veggie: veggie, patties: patties, pickles: pickles, mayo: mayo,
ketchup: ketchup, lettuce: lettuce, cook: cooked)
}
}
///main.swift
let builder = BurgerBuilder()
let burger:Burger = builder
.setVeggie(true)
.setMayo(false)
.setCooked(.wellDone)
.addPatty(false)
.buildBurgerObject(name: "Joe")
burger.printDescription()
複製程式碼
輸出結果
Name Joe
Vegie true
Patties 2
Pickles false
Mayo false
Ketchup true
Cook Well Done
複製程式碼
上面程式碼中設定屬性的方法返回值可以不寫。這裡這麼寫為了實現鏈式呼叫。
- cocoa中建造者模式的應用
//// cocoa 中 建造者模式的應用
var dateBuilder = DateComponents()
dateBuilder.hour = 10
dateBuilder.day = 6
dateBuilder.month = 9
dateBuilder.year = 1950
dateBuilder.calendar = Calendar(identifier: .gregorian)
if let date = dateBuilder.date {
print(date)
}
複製程式碼
輸出結果:
1950-09-06 02:00:00 +0000
複製程式碼
程式碼下載地址github.com/RockyAo/Des…