基本概念
建造者模式主要用于分离对象的创建和配置。调用组件负责提供数据。并负责将配置数据传递给建造者。建造者代替调用组件去创建响应的对象。
好处
- 使修改对象的默认值变简单
- 调用组件无需关心太多对象的构建过程
何时使用
- 对象创建需要进行复杂的配置。构造过程复杂。不想默认配置分散到程序的各个角落,此时可以使用建造者模式
示例程序
新建一个名为Builder的 OSX命令行程序
实现如下代码
///Food.swiftclass 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.swiftfinal 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.swiftlet builder = BurgerBuilder()let burger:Burger = builder .setVeggie(true) .setMayo(false) .setCooked(.wellDone) .addPatty(false) .buildBurgerObject(name: "Joe")burger.printDescription()复制代码
输出结果
Name JoeVegie truePatties 2Pickles falseMayo falseKetchup trueCook Well Done复制代码
上面代码中设置属性的方法返回值可以不写。这里这么写为了实现链式调用。
- cocoa中建造者模式的应用
cocoa 中 建造者模式的应用var dateBuilder = DateComponents()dateBuilder.hour = 10dateBuilder.day = 6dateBuilder.month = 9dateBuilder.year = 1950dateBuilder.calendar = Calendar(identifier: .gregorian)if let date = dateBuilder.date { print(date)}复制代码
输出结果:
1950-09-06 02:00:00 +0000复制代码
代码下载地址