객체를 사용하는 코드에서 객체 생성 부분을 떼어내 추상화한 패턴, 상속 관계에 있는 두 클래스에서 상위 클래스가 중요한 뼈대를 결정하고, 하위 클래스에서 객체 생성에 대한 구체적인 내용을 결정하는 패턴
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
};
main();