简体   繁体   English

什么是工厂,singleton,观察者设计模式? (哎呀)

[英]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?为了使我的代码更健壮并避免依赖 Pizza class 中的具体类,有什么更好的方法?

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?是使用 1) 工厂方法设计模式,2) singleton 设计模式,还是 3) 观察者设计模式或 4) 保持原样?

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如果将来您决定添加自定义披萨创建,那么使用 Builder 模式是有意义的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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