Skip to content

Instantly share code, notes, and snippets.

@radityagumay
Last active September 10, 2020 14:24
Show Gist options
  • Save radityagumay/f24236b193c9f993d096c228c70bf011 to your computer and use it in GitHub Desktop.
Save radityagumay/f24236b193c9f993d096c228c70bf011 to your computer and use it in GitHub Desktop.
A builder pattern in swift which follow Head First Design Pattern
class Contact {
private(set) lazy var name: String
private(set) lazy var phoneNumber: String
private(set) lazy var address: String
private(set) lazy var gender: String
private init(
name: String,
phoneNumber: String,
address: String,
gender: String
) {
self.name = name
self.phoneNumber = phoneNumber
self.address = address
self.gender = gender
}
class Builder {
private(set) lazy var name: String = ""
private(set) lazy var phoneNumber: String = ""
private(set) lazy var address: String = ""
private(set) lazy var gender: String = ""
func setName(name: String) -> Builder {
self.name = name
return self
}
func setPhoneNumber(phoneNumber: String) -> Builder {
self.phoneNumber = phoneNumber
return self
}
func setAddress(address: String) -> Builder {
self.address = address
return self
}
func setGender(gender: String) -> Builder {
self.gender = gender
return self
}
func build() -> Contact {
return Contact(
name: name,
phoneNumber: phoneNumber,
address: address,
gender: gender
)
}
}
}
let c = Contact.Builder()
.setName(name: "raditya")
.setAddress(address: "jakarta")
.setPhoneNumber(phoneNumber : "+62")
.setGender(gender : "male")
.build()
print(c.name)
print(c.address)
print(c.phoneNumber)
print(c.gender)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment