팩토리 패턴이란?
객체를 사용하는 코드에서 객체 생성 부분을 떼어내 추상화한 패턴이자 상속관계에 있는 두 클래스에서 상위 클래스가 중요한 벼대를 결정하고, 하위 클래스에서 객체 생성에 관한 구체적인 내용을 결정하는 패턴
<자바스크립트>
class Latte {
constructor() {
this.name = "latte"
}
}
class Espresso {
constructor() {
this.name = "Espresso"
}
}
class LatteFactory() {
static createCoffee() {
return new Latte();
}
}
class EspressoFactory() {
static createCoffee() {
return new Espresso();
}
}
const factoryList = { LatteFactory , EspressoFactory }
class CoffeeFactory {
static createCoffee(type) {
const factory = factoryList[type]
return factory.createCoffee()
}
}
const main = () => {
const coffee = CoffeeFactory.createCoffee("LatteFactory")
console.log(coffee.name)
}
main()
<자바>
abstract class Coffee {
public abstract int getPrice();
@Override
public String toString() {
return "Hi this coffee is " + this.getPrice();
}
}
class CoffeeFactory {
public static Coffee getCoffee(String type, int price){
if("Latte".equalsIgnoreCase(type)) return new Latte(price);
else if("Americano".equalsIgnoreCase(type)) return new Americano(price);
else {
return new DefaultCoffee();
}
}
}
class DefaultCoffee extends Coffee {
private int price;
public DefaultCoffee() {
this.price = -1;
}
@Override
public int getPrice() {
return this.price;
}
}
class Latte extends Coffee {
private int price;
public Latte() {
this.price = -1;
}
@Override
public int getPrice() {
return this.price;
}
}
class Americano extends Coffee {
private int price;
public Americano() {
this.price = -1;
}
@Override
public int getPrice() {
return this.price;
}
}
public class HelloWorld {
public static void main(String[] args) {
Coffee latte = CoffeeFactory.getCoffee("Latte", 4000);
Coffee ame = CoffeeFactory.getCoffee("Americano", 3000);
System.out.println("Factory latte ::" + latte);
System.out.println("Factory ame ::" + ame);
}
}
출처: 면접을 위한 CS전공 지식