팩토리 패턴
객체를 사용하는 코드에서 객체 생성 부분을 떼어내 추상화한 패턴이자 상속 관계에 있는 두 클래스에서 상위 클래스가 중요한 뼈대를 결정하고, 하위 클래스에서 객체 생성에 관한 구체적인 내용을 결정하는 패턴
즉, 객체 생성 처리를 서브 클래스로 분리 해 처리하도록 캡슐화하는 패턴으로 객체의 생성 코드를 별도의 클래스/메서드로 분리함으로써 객체 생성의 변화에 대비하는 데 유용하다.
주로 인터페이스 타입으로 오브젝트를 반환하므로 Super Class에서는 Sub Class에서 정확히 어떤 클래스의 오브젝트를 만들어 반환할지 알지 못한다.
예시
라떼 레시피와 아메리카노 레시피, 우유 레시피 라는 구체적인 내용이 들어있는 하위 클래스가 컨베이어 벨트를 통해 전달 되고,
상위 클래스인 바리스타 공장에서 이 레시피들을 토대로 우유 등을 생산하는 생산공정이다
자바에서의 팩토리 패턴
if ("Latte".equalsIgnoreCase(type))을 통해 문자열 비교 기반으로 로직이 구선됨을 알 수 있다
Enum or Map 을 이용하여 if 문을 쓰지 않고 매핑 할 수 있다.
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(int price) {
this.price = price;
}
@Override
public int getPrice() {
return this.price;
}
class Americano extends Coffee {
private int price;
public Americano(int price) {
this.price = price;
}
@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);
}
}
}
/*
Factory latte: Hi this coffee is 4000 Factory ame ::Hi this coffee is 3000
*/
'CS 공부' 카테고리의 다른 글
옵저버 패턴 (1) | 2024.02.13 |
---|---|
프록시 패턴과 프록시 서버 (0) | 2024.02.13 |
전략패턴 (Strategy Pattern) (0) | 2024.02.08 |
[DB] 조인의 종류 및 원리 (0) | 2024.01.25 |