Abstract Factory 패턴은 매트릭스 관계를 가진 클래스 오브젝트를 생성할 때 유용하다.
핵심은 각각의 테마를 가진 오브젝트를 하나의 팩토리에서 만든다는 것이다.
// Protocols for components
protocol Button {
func click()
}
protocol CheckBox {
func check()
}
protocol ScrollBar {
func scroll()
}
// Dark theme implementations
class DarkButton: Button {
func click() {
print("dark click")
}
}
class DarkCheckBox: CheckBox {
func check() {
print("dark check")
}
}
class DarkScrollBar: ScrollBar {
func scroll() {
print("dark scroll")
}
}
// Light theme implementations
class LightButton: Button {
func click() {
print("light click")
}
}
class LightCheckBox: CheckBox {
func check() {
print("light check")
}
}
class LightScrollBar: ScrollBar {
func scroll() {
print("light scroll")
}
}
// UIFactory protocol and its implementations
protocol UIFactory {
func getButton() -> Button
func getCheckBox() -> CheckBox
func getScrollBar() -> ScrollBar
}
class DarkUIFactory: UIFactory {
func getButton() -> Button {
return DarkButton()
}
func getCheckBox() -> CheckBox {
return DarkCheckBox()
}
func getScrollBar() -> ScrollBar {
return DarkScrollBar()
}
}
class LightUIFactory: UIFactory {
func getButton() -> Button {
return LightButton()
}
func getCheckBox() -> CheckBox {
return LightCheckBox()
}
func getScrollBar() -> ScrollBar {
return LightScrollBar()
}
}
// Using the factories
let darkFactory = DarkUIFactory()
let darkButton = darkFactory.getButton()
let darkCheckBox = darkFactory.getCheckBox()
let darkScrollBar = darkFactory.getScrollBar()
darkButton.click()
darkCheckBox.check()
darkScrollBar.scroll()
/*
dark click
dark check
dark scroll
*/
let lightFactory = LightUIFactory()
let lightButton = lightFactory.getButton()
let lightCheckBox = lightFactory.getCheckBox()
let lightScrollBar = lightFactory.getScrollBar()
lightButton.click()
lightCheckBox.check()
lightScrollBar.scroll()
/*
light click
light check
light scroll
*/