컴퓨터 공학 & 통신
[개념 정리/디자인 패턴] 생성 패턴 - 팩토리 패턴
왈왈디
2023. 7. 4. 11:29
728x90
팩토리 패턴(Factory pattern)
팩토리 패턴이란 상속 관계에 있는 두 클래스에서
상위 클래스가 중요한 뼈대를 결정하고,
하위 클래스에서 객체 생성에 관한 구체적인 내용을 결정하는 패턴이다.
상위 클래스에서는 객체 생성 방식에 관여하지 않고,
객체 생성 로직은 하위 클래스에서만 관리 되기 때문에
역할이 분리되어 유연성과 유지 보수성이 높다.
예시
아래는 자바스크립트 코드 예시이다.
class CoffeeFactory {
static createCoffee(type){
const factory = factoryList[type]
return factory.createCoffee()
}
}
class Latte {
constructor(){
this.name = "latte"
}
}
class Espresso {
constructor(){
this.name = "Espresso"
}
}
class LatteFactory extends CoffeeFactory {
static createCoffee(){
return new Latte()
}
}
class EspressoFactory extends CoffeeFactory {
static createCoffee(){
return new Espresso()
}
}
const factoryList = { LatteFactory, EspressoFactory }
const main = () => {
//라떼 커피를 주문한다.
const coffee = CoffeeFactory.createCoffee("LatteFactory")
//커피 이름을 부른다.
console.log(coffee.name)//Latte
}
참고: inflearn 강의 'CS 지식의 정석 - 큰돌'
728x90