팩토리 패턴
1. 팩토리 패턴이란?
2. 자바스크립트에서의 팩토리 패턴
2-1. 팩토리 패턴 적용 전
class Car {
constructor(props) {
this.name = props.name;
this.year = props.year;
this.price = props.price;
}
getDiscount() {
this.price -= this.sale;
}
getInfo() {
return this.name + "의 가격은 " + this.price + "원 입니다.";
}
}
class Avante extends Car {
constructor(props) {
super(props);
this.sale = Math.floor(props.price / 50);
}
}
class Sonata extends Car {
constructor(props) {
super(props);
this.sale = Math.floor(props.price / 60);
}
}
class Grandeur extends Car {
constructor(props) {
super(props);
this.sale = Math.floor(props.price / 70);
}
}
const getFinalPrice = (info) => {
let car;
if (info.name.toLowerCase() === "avante") {
car = new Avante(info);
} else if (info.name.toLowerCase() === "sonata") {
car = new Sonata(info);
} else if (info.name.toLowerCase() === "grandeur") {
car = new Grandeur(info);
}
car.getDiscount();
return car.getInfo();
};2-2. 팩토리 패턴 적용 후
2-3. 자동차의 최종 가격을 반환하는 함수
2-4. Array.map() 메서드를 사용한 인스턴스 생성

출처
Last updated


