[디자인패턴] 팩토리 메소드 패턴 with python


Head First Design Pattern 에 소개되는 예제를 파이썬으로 구현하였습니다.


팩토리 메소드 패턴(Factory Method Pattern)

책에서는 팩토리 메소드 패턴을 아래와 같이 설명하고 있다.

팩토리 메소드 패턴에서는 객체를 생성하기 위한 인터페이스를 정의하는데, 어떤 클래스의 인스턴스를 만들지는 서브클래스에서 결정하게 만든다.

예제 UML

예제 구현

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from abc import ABCMeta, abstractmethod

#Product Class
class Pizza(metaclass=ABCMeta):
def __init__(self):
self.name = ''
self.dough = ''
self.sauce = ''
self.toppings = []

def prepare(self):
print("Preparing "+ self.name)
print("Tossing Dough...")
print("Adding sauce")
print("Adding toppings")

def bake(self):
print("Bake for 25 minutes at 350")

def cut(self):
print("Cutting the pizza into diagonal slices")

def box(self):
print("Pizza in official pizzastore box")

def getName(self):
return self.name


class NYStyleCheesePizza(Pizza):
def __init__(self):
self.name = "NY Style Sauce and Cheese Pizza"
self.dough = "Thin Crust Dough"
self.sauce = "Marinara Sauce"
self.toppings = ["Grated Reggino Cheese"]


class NYStyleVeggiPizza(Pizza):
def __init__(self):
self.name = "NY Style Sauce and Veggi Pizza"
self.dough = "Thin Rice Dough"
self.sauce = "Tomato Sauce"
self.toppings = ["Vegetable", "바질 페스토"]


class NYStylePepperoniPizza(Pizza):
def __init__(self):
self.name = "NY Style Sauce and Pepperoni Pizza"
self.dough = "Thin Sweet Potato Dough"
self.sauce = "Tomato Sauce"
self.toppings = ["Peppronies"]

#Creator Class
class PizzaStore(metaclass=ABCMeta):
@abstractmethod
def createPizza(self):
pass

def orderPizza(self, pizza_type):
pizza = self.createPizza(pizza_type)
pizza.prepare()
pizza.bake()
pizza.cut()
pizza.box()

return pizza


class NYPizzaStore(PizzaStore):
def createPizza(self, item):
if item == "cheese":
return NYStyleCheesePizza()
elif item == "veggi":
return NYStyleVeggiPizza()
elif item == "pepperoni":
return NYStylePepperoniPizza()

테스트

뉴욕 스타일 치즈 피자, 채소 피자 주문

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

nystore = NYPizzaStore()
pizza = nystore.orderPizza("cheese")
print(f"Jeanie ordered a {pizza.getName()}")
#Preparing NY Style Sauce and Cheese Pizza
#Tossing Dough...
#Adding sauce
#Adding toppings
#Bake for 25 minutes at 350
#Cutting the pizza into diagonal slices
#Pizza in official pizzastore box
#Jeanie ordered a NY Style Sauce and Cheese Pizza


nystore = NYPizzaStore()
pizza = nystore.orderPizza("veggi")
print(f"Jeanie ordered a {pizza.getName()}")
#Preparing NY Style Sauce and Veggi Pizza
#Tossing Dough...
#Adding sauce
#Adding toppings
#Bake for 25 minutes at 350
#Cutting the pizza into diagonal slices
#Pizza in official pizzastore box
#Jeanie ordered a NY Style Sauce and Veggi Pizza

Comments