Created
April 19, 2016 01:19
-
-
Save miguelbassila/420253b2d9ec0012ac4c36ca4fddc934 to your computer and use it in GitHub Desktop.
Design Pattern: Builder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PersonBuilder { | |
private final var name: String | |
private final var age: String? | |
private final var gender: String? | |
init(name: String) { | |
self.name = name | |
} | |
func with(age age: String) -> Self { | |
self.age = age | |
return self | |
} | |
func with(gender gender: String) -> Self { | |
self.gender = gender | |
return self | |
} | |
func build() -> Person { | |
return Person(builder: self) | |
} | |
} | |
struct Person { | |
let name: String | |
let age: String? | |
let gender: String? | |
init(builder: PersonBuilder) { | |
name = builder.name | |
age = builder.age | |
gender = builder.gender | |
} | |
} | |
let cegela = PersonBuilder(name: "Cegela").with(age: "20").with(gender: "M").build() | |
let mucuge = PersonBuilder(name: "Mucuge").with(gender: "M").with(age: "25").build() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Look this example of Builder using closure: https://github.com/elo7/Nayau/blob/master/nayau/Message.swift