디자인 패턴 종류
빌더 패턴
- 클래스에서 생성할 객체를 멤버변수로 가짐
- 함수로 자기 자신을 내뱉음
- 마지막에 build()
첫번째 방식
struct Pet {
var name: String? = nil
var age: Int? = nil
}
class PetBuilder{
private var pet : Pet = Pet()
func withName(_ name: String) -> Self {
pet.name = name
return self
}
func withAge(_ age: Int) -> Self {
pet.age = age
return self
}
func build() -> Pet {
return self.pet
}
}
let myPet = PetBuilder()
.withName("a")
.withAge(10)
.build()
두번째 방식 (closure)
struct Pet {
var name: String? = nil
var age: Int? = nil
init(){}
init(builder: SecondPetBuilder){
self.name = builder.name
self.age = builder.age
}
}
class SecondPetBuilder{
var name: String? = nil
var age: Int? = nil
typealias BuilderClosure = (SecondPetBuilder) -> ()
init(buildClosure: BuilderClosure){
buildClosure(self)
}
}
let petBuilder = SecondPetBuilder { builder in
builder.name = "댕댕이"
builder.age = 10
}
let mySecondPet = Pet(builder: petBuilder)