팩토리패턴이란 상속 관계에 있는 두 클래스에서 상위 클래스가 중요한 뼈대를 결정하고, 하위 클래스에서 객체 생성에 관한 구체적인 내용을 결정하는 패턴이다.
상위 클래스에서는 객체 생성방식에 대해 알 필요가 없어져 유연성을 갖게 되며 객체 생성 로직은 하위클래스에서만 관리 되기 때문에 유지보수성이 증가된다는 장점이 있다.
// enum타입 정의
enum CoffeeType {
LATTE,
ESPRESSO
}
// 상위클래스인 Coffee(추상클래스)
abstract class Coffee {
protected String name;
public String getName() {
return name;
}
}
// 상위 Coffee클래스를 상속받는 Latte 클래스
class Latte extends Coffee {
public Latte() {
name = "latte";
}
}
// 상위 Coffee클래스를 상속받는 Espresso 클래스
class Espresso extends Coffee {
public Espresso() {
name = "Espresso";
}
}
class CoffeeFactory {
public static Coffee createCoffee(CoffeeType type) {
switch (type) {
case LATTE:
return new Latte();
case ESPRESSO:
return new Espresso();
default:
throw new IllegalArgumentException("Invalid coffee type: " + type);
}
}
}