빌더 패턴이란 복합 객체의 생성 과정과 표현 방법을 분리하여 동일한 생성 절차에서 서로 다른 표현 결과를 만들 수 있게 하는 패턴이다. -위키백과
import Foundation
struct MacBook {
let color: String
let memory: Int
let storage: String
let hasTouchBar: Bool
}
class MacBookBuilder {
private var color = "Space Gray"
private var memory = 16
private var storage = "256GB"
private var hasTouchBar = false
func setColor(_ color: String) -> MacBookBuilder {
self.color = color
return self
}
func setMemory(_ memory: Int) -> MacBookBuilder {
self.memory = memory
return self
}
func setStorage(_ storage: String) -> MacBookBuilder {
self.storage = storage
return self
}
func setHasTouchBar(_ has: Bool) -> MacBookBuilder {
self.hasTouchBar = has
return self
}
func build() -> MacBook {
return MacBook(color: color, memory: memory, storage: storage, hasTouchBar: hasTouchBar)
}
}
let builder = MacBookBuilder()
let macBook1 = builder.setColor("Sliver").setMemory(32).setStorage("512GB").setHasTouchBar(true).build()
let macBook2 = builder.setMemory(32).setStorage("1TB").build()
let macBook3 = builder.build()
struct Pizza {
var size: Int
var cheese: Bool
var pepperoni: Bool
var sausage: Bool
var mushrooms: Bool
var olives: Bool
}
class PizzaBuilder {
private var size: Int = 12
private var cheese: Bool = false
private var pepperoni: Bool = false
private var sausage: Bool = false
private var mushrooms: Bool = false
private var olives: Bool = false
func setSize(_ size: Int) -> PizzaBuilder {
self.size = size
return self
}
func setCheese(_ cheese: Bool) -> PizzaBuilder {
self.cheese = cheese
return self
}
func setPepperoni(_ pepperoni: Bool) -> PizzaBuilder {
self.pepperoni = pepperoni
return self
}
func setSausage(_ sausage: Bool) -> PizzaBuilder {
self.sausage = sausage
return self
}
func setMushrooms(_ mushrooms: Bool) -> PizzaBuilder {
self.mushrooms = mushrooms
return self
}
func setOlives(_ olives: Bool) -> PizzaBuilder {
self.olives = olives
return self
}
func build() -> Pizza {
return Pizza(
size: size,
cheese: cheese,
pepperoni: pepperoni,
sausage: sausage,
mushrooms: mushrooms,
olives: olives
)
}
}
// Builder Pattern을 사용하여 Pizza 객체를 생성하는 예
let pizza = PizzaBuilder()
.setSize(16)
.setCheese(true)
.setPepperoni(true)
.setMushrooms(true)
.build()
제가 학습한 내용을 요약하여 정리한 것입니다. 내용에 오류가 있을 수 있으며, 어떠한 피드백도 감사히 받겠습니다.
감사합니다.