본문 바로가기

OOP/디자인 패턴

Factory 패턴

1. 필요성

자식 클래스가 많은 곳에서 생성되거나 자식 클래스들에 대해 드러내지 않고 숨기고 싶을 경우 팩토리 패턴을 사용한다.

대표적으론 라이브러리나 프레임워크에서 팩토리에 상수값을 넘겨줘 객체를 리턴받는 등의 예를 있다.

, 라이브러리나 프레임워크를 사용할 개발자들이 해당 객체에 대해 깊이 필요가 없이 간편하게 생성해 사용할 있도록하는 장점이 있다.

 

 

2. 컴포넌트 class 생성

abstract class Component {
    init {
        Log.e("component","name : ${getName()}")
    }
    protected abstract fun getName() : String
}


class Button : Component(){
    override fun getName() : String{
        return "Button"
    }
}


class Switch : Component(){
    override fun getName() : String{
        return "Switch"
    }
}


class Dropdown : Component(){
    override fun getName() : String{
        return "Dropdown"
    }
}

 

 

3. Factory class 생성

enum class Usage{
    PRESS,TOGGLE,EXPAND
}

class ComponentFactory {
    fun getComponent(_usage : Usage) : Component? {
        var component : Component? = null
        when(_usage){
            Usage.PRESS->{
                component =  Button()
            }
            Usage.TOGGLE->{
                component = Switch()
            }
            Usage.EXPAND->{
                component =  Dropdown()
            }
            else->{}
        }
        return component
    }
}

 

 

4.  Factory 패턴 사용 / 미사용 비교 예시

class ComponentGroup {
    private val componentFactory : ComponentFactory = ComponentFactory()
    var component : Component? = null
    var component2 : Component? = null
    var component3 : Component? = null

    fun makeComWithoutFactory(){
        component = Button()
        component2 = Switch()
        component3 = Dropdown()
    }

    fun makeComWithFactory(){
        component = componentFactory.getComponent(Usage.PRESS)
        component2 = componentFactory.getComponent(Usage.TOGGLE)
        component3 = componentFactory.getComponent(Usage.EXPAND)
    }
}

 

 

'OOP > 디자인 패턴' 카테고리의 다른 글

DI (Dependency Injection/의존성 주입)  (0) 2021.07.17
abstract-factory method 패턴  (0) 2021.07.08
Decorator 패턴  (0) 2021.07.05
Template 패턴  (0) 2021.07.03
Facade 패턴  (0) 2021.06.28