Builder 建造者模式
Extracting the instance’s building code from the instance’s class, and put the code into a “Builder” object to do the build work. So we can build different complex instance by using different composition of the builder method. Besides, Add a “director” to manage the calling form client.
将对象的构造代码从对象的产品类代码中抽离出来,将这些代码放置在一个名为 “生成器” 的独立对象中。 所以,我们可以通过在建造方法中使用不同的组合,来创建不同的复杂实例。并且,增加一个 “指挥者” 来管理那些来自外界客户对调用。
// Director
class HouseDirector{
var builder: HouseBuilder
init (builder: HouseBuilder) {
self.builder = builder
}
func changeBuilder(bulider: HouseBuilder) {
self.builder = bulider
}
// The function "make" define the house must built by some componets.
func make(type: String) {
builder.reset()
if type == "simple" {
builder.buildA()
} else {
builder.buildB()
builder.buildC()
}
}
}
// Builder
protocol HouseBuilder {
func reset()
func buildA()
func buildB()
func buildC()
}
class Builder1: HouseBuilder {
private var result: Product1?
func reset() {
result = Product1()
}
func buildA() {
}
func buildB() {
}
func buildC() {
}
func getResult() -> Product1? {
return result
}
}
class Builder2: HouseBuilder {
private var result: Product2?
func reset() {
result = Product2()
}
func buildA() {
}
func buildB() {
}
func buildC() {
}
func getResult() -> Product2? {
return result
}
}
class Product1 {
}
class Product2 {
}
let b = Builder1()
let director = HouseDirector(builder: b)
director.make(type: "complex")