Assume that there will be more Pizzas in the future. In order to make my code more robust and avoid dependencies on concrete classes from the Pizza class, what would be a better approach?
class Pizza:
def order(pizza_type):
pizza = none
if pizza_type == "cheese":
pizza = CheezePizza()
elif pizza_type == "pepperoni":
pizza = PepperoniPizza()
elif pizza_type == "veggie":
pizza = VeggiePizza()
pizza.prepare()
pizza.bake()
return pizza
Is it better to use the 1) factory method design pattern, 2) singleton design pattern, or the 3) observer design pattern or 4) keep it as it is?
I believe what you're doing here is called "facade pattern" and IMHO it is best suited for the purpose - however, I'd implement it slightly differently:
class Pizza:
pizza_types = {
"cheese": CheesePizza,
"pepperoni": PepperoniPizza,
"veggie": VeggiePizza
}
def order(pizza_type):
pizza_constructor = Pizza.pizza_types.get(pizza_type)
pizza = pizza_constructor() # instantiate the right type of pizza
pizza.prepare()
pizza.bake()
return pizza
You are combining pizza 'creation' and 'preparation' together in this one method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.