1. 필요성
추상 팩토리 패턴은 팩토리 패턴에서 팩토리를 추상화한 패턴이다.
Factory 패턴
1. 필요성 이처럼 Component를 상속받은 자식들이 많은 곳에서 생성된다고 가정하자. 객체 생성이 많이 이루어지지 않는다면 큰 문제가 없지만 많이 이뤄지는 상황에서 자식 클래스의 생성자가 변
leehochang.tistory.com
예를 들어 라이트 모드와 다크 모드에서 생성되는 컴포넌트들이 다를 수 있다. 라이트 모드에선 라이트 버튼, 스위치, 드롭다운/ 다크 모드에선 다크 버튼, 스위치, 드롭다운 등을 생성해야 한다고 가정하자. 이러한 경우에 추상 팩토리 패턴을 적용할 수 있다.
이를 구조로 그려보면
이처럼 추상 클래스나 인터페이스를 만들어서 팩토리를 추상화하는 방식이다.
2. 추상 클래스 및 팩토리 구현
enum class Usage{
PRESS,TOGGLE,EXPAND
}
abstract class Factory{
abstract fun getCom(_usage: Usage) : Component
}
class LightFactory : Factory() {
override fun getCom(_usage: Usage) : Component {
when(_usage){
Usage.PRESS->{
return LightButton()
}
Usage.TOGGLE->{
return LightSwitch()
}
Usage.EXPAND->{
return LightDropdown()
}
}
}
}
class DarkFactory : Factory() {
override fun getCom(_usage: Usage) : Component {
when(_usage){
Usage.PRESS->{
return DarkButton()
}
Usage.TOGGLE->{
return DarkSwitch()
}
Usage.EXPAND->{
return DarkDropdown()
}
}
}
}
3. 컴포넌트 구현
abstract class Component {
init {
Log.e("component","name : ${getName()}")
}
protected abstract fun getName() : String
}
class LightButton : Component(){
override fun getName() : String{
return "LightButton"
}
}
class DarkButton : Component(){
override fun getName() : String{
return "DarkButton"
}
}
class LightSwitch : Component(){
override fun getName() : String{
return "LightSwitch"
}
}
class DarkSwitch : Component(){
override fun getName() : String{
return "DarkSwitch"
}
}
class LightDropdown : Component(){
override fun getName() : String{
return "LightDropdown"
}
}
class DarkDropdown : Component(){
override fun getName() : String{
return "DarkDropdown"
}
}
4. main()
val lightFactory = LightFactory()
val darkFactory = DarkFactory()
var component : Component? = null
var component2 : Component? = null
var component3 : Component? = null
component = lightFactory.getCom(Usage.PRESS)
component2 = lightFactory.getCom(Usage.TOGGLE)
component3 = lightFactory.getCom(Usage.EXPAND)
component = darkFactory.getCom(Usage.PRESS)
component2 = darkFactory.getCom(Usage.TOGGLE)
component3 = darkFactory.getCom(Usage.EXPAND)
'OOP > 디자인 패턴' 카테고리의 다른 글
Mediator 패턴 (0) | 2021.07.17 |
---|---|
DI (Dependency Injection/의존성 주입) (0) | 2021.07.17 |
Factory 패턴 (0) | 2021.07.07 |
Decorator 패턴 (0) | 2021.07.05 |
Template 패턴 (0) | 2021.07.03 |