简体   繁体   中英

What is factory, singleton, observer design pattern? (OOP)

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.

  1. You can separate them to begin with
  2. You can think of using parameterized factory method to create all pizza types
  3. If in future, you decide to add custom pizza creation then it makes sense to use Builder pattern

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM