建造者模式是将一个复杂的对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示.
执行者:
class Director {
var builder:Builder?
convenience init(builder:Builder) {
self.init()
self.builder = builder
}
func construct() {
self.builder?.makeTop()
self.builder?.makeBody()
self.builder?.makeBottom()
}
}
建造者:
class Builder {
func makeTop() { }
func makeBody() { }
func makeBottom() { }
}
class WebBuilder: Builder {
override func makeTop() {
print("FlyElephant---网页制作");
}
override func makeBody() {
print("FlyElephant---<Html></Html>")
}
override func makeBottom() {
print("FlyElephant----Footer")
}
}
class MobileBuilder: Builder {
override func makeTop() {
print("FlyElephant---移动制作");
}
override func makeBody() {
print("FlyElephant---UITableView")
}
override func makeBottom() {
print("FlyElephant----tabBar")
}
}
测试代码:
let webBuilder:Builder = WebBuilder()
var director:Director = Director(builder: webBuilder)
director.construct()
let mobileBuilder:Builder = MobileBuilder()
director = Director(builder: mobileBuilder)
director.construct()