Nothing Special   »   [go: up one dir, main page]

Skip to content

Instantly share code, notes, and snippets.

@thoretton-edwin
Last active April 11, 2018 09:36
Show Gist options
  • Save thoretton-edwin/d8176bf1c09d075e2cb5e3be35499242 to your computer and use it in GitHub Desktop.
Save thoretton-edwin/d8176bf1c09d075e2cb5e3be35499242 to your computer and use it in GitHub Desktop.
Swift builder pattern
import Foundation
//sources :
//https://blog.xebia.fr/2016/12/28/design-pattern-builder-et-builder-sont-dans-un-bateau/
//https://jlordiales.me/2012/12/13/the-builder-pattern-in-practice/
//https://pastebin.com/CXyxh658
class Window { }
class Door { }
class Wall { }
class Roof { }
class House {
var windows: [Window]?
var doors: [Door]?
var walls: [Wall]?
var roof: Roof?
init(builder: HouseBuilder) {
self.walls = builder.walls
self.roof = builder.roof
self.doors = builder.optionalDoors
self.windows = builder.optionalWindows
}
}
public class HouseBuilder {
var walls: [Wall]
var roof: Roof
var optionalWindows: [Window]?
var optionalDoors: [Door]?
public init() {
//have to initialize all fields ...
walls = [Wall]()
roof = Roof()
}
func getWallsRequiredBuilder(roof: Roof) -> WallsRequiredBuilder{
self.roof = roof
return WallsRequiredBuilder(builder: self)
}
public class WallsRequiredBuilder {
private let builder: HouseBuilder
init(builder: HouseBuilder) {
self.builder = builder
}
func setWalls(walls: [Wall]) -> OptionalWindowsBuilder {
builder.walls = walls
return OptionalWindowsBuilder(builder: builder)
}
}
public class OptionalWindowsBuilder {
private let builder: HouseBuilder
init(builder: HouseBuilder) {
self.builder = builder
}
func build() -> House {
return House(builder: builder)
}
}
}
import Foundation
let walls = [Wall(), Wall(), Wall(), Wall()]
let windows = [Window(), Window()]
let roof = Roof()
let house = HouseBuilder()
.getWallsRequiredBuilder(roof: roof)
.setWalls(walls: walls)
.build()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment