Factory 패턴은 객체 생성 로직을 클라이언트 코드에서 분리하고, 인스턴스를 생성할 때 이를 팩토리 클래스에서 처리하도록 합니다. 따라서 객체 생성 로직을 별도로 분리하므로, 유연성과 유지보수성을 높일 수 있습니다.
public abstract class Coffee {
protected String name;
public String getName() {
return name;
}
}
public class Espresso extends Coffee {
public Espresso() {
name = "espresso";
}
}
public class Latte extends Coffee {
public Latte() {
name = "latte";
}
}
Coffee 와 하위 클래스 Espresso, Latte 생성public enum CoffeeType {
LATTE, ESPRESSO
}
public class CoffeeFactory {
public static Coffee createCoffee(CoffeeType type) {
switch (type){
case LATTE:
return new Latte();
case ESPRESSO:
return new Espresso();
default:
throw new IllegalArgumentException();
}
}
}
CoffeeType 을 인자로 받아, type 에 맞게 적합한 인스턴스를 생성해주는 CoffeeFactory 클래스 생성Coffee 타입으로 다양한 하위 클래스 객체를 처리함Coffee 타입으로 반환되지만, 실제로 생성되는 객체는 Latte, Espresso와 같은 구체적인 서브 클래스임public class Client {
public static void main(String[] args) {
Coffee coffee = CoffeeFactory.createCoffee(CoffeeType.LATTE);
System.out.println(coffee.getName()); // latte
}
}
CoffeeFactory 에 위임함Latte나 Espresso 객체를 반환하여 그에 맞는 메서드가 호출됩니다.