1. 정의
- 객체를 생성할 때 필요한 인터페이스를 만든다. 어떤 클래스의 인스턴스를 만들지는 서브클래스에서 결정한다.
- 팩토리 메소드를 사용하면 인스턴스를 만드는 일을 서브클래스에 맡길 수 있다.
💡 추상 팩토리를 통해 일관된 방법으로 객체를 생성하는데, 팩토리 메소드 패턴을 통해 구체적인 객체를 서브클래스에서 생성되게 한다.
2. 예시
- 서울과 제주 피자 체인점에서 피자를 주문한다.
3. 그림
4. 클래스 다이어그램
5. 코드
public class Client {
public static void main(String[] args){
PizzaStore seoul = new SeoulPizzaStore();
seoul.orderPizza("cheese").getDescription();
seoul.orderPizza("pepperoni").getDescription();;
System.out.println("------");
PizzaStore jeju = new JejuPizzaStore();
jeju.orderPizza("cheese").getDescription();;
jeju.orderPizza("pepperoni").getDescription();;
}
}
/* 출력
서울 치즈 피자
서울 페페로니 피자
------
제주 치즈 피자
제주 페페로니 피자
*/
public abstract class PizzaStore {
abstract Pizza createPizza(String type);
public Pizza orderPizza(String type){
Pizza pizza = createPizza(type);
return pizza;
}
}
public class SeoulPizzaStore extends PizzaStore {
@Override
Pizza createPizza(String type) {
if (type.equals("cheese")) {
return new SeoulCheesePizza();
}
return new SeoulPepperoniPizza();
}
}
public class JejuPizzaStore extends PizzaStore {
@Override
Pizza createPizza(String type) {
if (type.equals("cheese")) {
return new JejuCheesePizza();
}
return new JejuPepperoniPizza();
}
}
public abstract class Pizza {
String description;
void getDescription(){
System.out.println(this.description);
}
}
public class SeoulCheesePizza extends Pizza{
SeoulCheesePizza(){
this.description = "서울 치즈 피자";
}
}
public class SeoulPepperoniPizza extends Pizza{
public SeoulPepperoniPizza() {
this.description = "서울 페페로니 피자";
}
}
public class JejuCheesePizza extends Pizza{
public JejuCheesePizza() {
this.description = "제주 치즈 피자";
}
}
public class JejuPepperoniPizza extends Pizza{
public JejuPepperoniPizza() {
this.description = "제주 페페로니 피자";
}
}
https://github.com/kang-seongbeom/design_pattern
💡 Github에서 디자인 패턴 코드를 볼 수 있습니다.
6. 설명
- Pizza는 객체 생성에 필요한 인터페이스다.
- cheese인지 pepperoni인지는 서브클래스에서 결정한다.
- Client는 PizzaStore을 통해 일관되게 객체를 생성하고(추상 팩토리), orderPizza()를 통해 구체적인 인스턴스를 서브클래스에서 결정할 수 있게 한다(팩토리 메소드).
'디자인 패턴' 카테고리의 다른 글
디자인 패턴 - 커맨드 패턴(Command Pattern) (0) | 2022.11.17 |
---|---|
디자인 패턴 - 싱글톤 패턴(Singleton Pattern) (0) | 2022.11.17 |
디자인 패턴 - 추상 팩토리 패턴(Abstract Factory Pattern) (0) | 2022.11.17 |
디자인 패턴 - 데코레이터 패턴(Decorator Pattern) (0) | 2022.11.17 |
디자인 패턴 - 옵저버 패턴(Observer Pattern) (0) | 2022.11.17 |