CS/디자인 패턴
팩토리 패턴 (Factory Pattern)
longbeom
2022. 9. 14. 14:28
팩토리 패턴(Factory Pattern)이란?
객체를 사용하는 코드에서 객체 생성 부분을 떼어내 추상화한 패턴이다.
상속 관계에 있는 두 클래스에서 상위 클래스가 중요한 뼈대를 결정하고, 하위 클래스에서 객체 생성에 관한 구체적인 내용을 결정하는 패턴이다.
핵심 개념은 추상화와 다형성이다.
팩토리 패턴의 장단점
- 장점
- 상위 클래스와 하위 클래스가 분리되기 때문에 느슨한 결합을 가질 수 있다.
- 상위 클래스에서는 인스턴스 생성 방식에 대해 전혀 알 필요가 없기 때문에 유연하다.
- 객체 생성 로직이 분리되어 있어서 유지 보수에 유리하다.
- 단점
- 다른 타입의 객체가 필요할 때 마다 하위 클래스가 추가되어야 한다.
자바에서의 팩토리 패턴
abstract class Coffee {
public abstract int getPrice();
@Override
public String toString() {
return "Hi this coffee is " + this.getPrice();
}
}
class CoffeeFactory {
public static Coffee getCoffee(CoffeeType type, int price) {
if (type == CoffeeType.LATTE) return new Latte(price);
else if (type == CoffeeType.AMERICANO) 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(int price) {
this.price = price;
}
@Override
public int getPrice() {
return price;
}
}
class Americano extends Coffee {
private int price;
public Americano(int price) {
this.price = price;
}
@Override
public int getPrice() {
return price;
}
}
enum CoffeeType {
LATTE,
AMERICANO,
DEFAULT
}
public class FactoryPattern {
public static void main(String[] args) {
Coffee latte = CoffeeFactory.getCoffee(CoffeeType.LATTE, 4000);
Coffee americano = CoffeeFactory.getCoffee(CoffeeType.AMERICANO, 3000);
System.out.println("Factory Latte : " + latte);
System.out.println("Factory Americano : " + americano);
}
}
/* 출력
Factory Latte : Hi this coffee is 4000
Factory Americano : Hi this coffee is 3000
*/
Coffee라는 상위 클래스에서 뼈대를 결정하고, [DefaultCoffee, Latte, Americano]라는 하위 클래스에서 객체 생성의 구체적인 내용을 결정한다.