Design pattern 23 of a simple factory pattern

basic introduction

  1. Simple factory pattern belongs create schema, but does not belong to one of 23 kinds of GOF design patterns. Simple factory mode 由一个工厂对象决定创建出哪一种产品类的实例. Simple factory pattern is the factory model family is the most simple and practical mode
  2. Simple factory pattern: creating a definition of object classes, the instance of the object class to encapsulate behavior (code)
  3. In software development, when we use a lot of create some kind, or if some sort of a batch of objects, it will use the factory pattern.

demand

Look at a pizza project: To facilitate the pizza kind of expansion, to facilitate maintenance, complete the pizza-ordering capability.
Pizza abstract class design, as follows:
Here Insert Picture Description

Traditional solutions

class OrderPizza {
  var orderType: String = _
  var pizza: Pizza = _
  breakable {
    do {
      println("请输入pizza的类型")
      orderType = StdIn.readLine()
      if (orderType.equals("greek")) {
        this.pizza = new GreekPizza
      } else if (orderType.equals("pepper")) {
        this.pizza = new PepperPizza
      } else {
        break()
      }
      this.pizza.prepare()
      this.pizza.bake()
      this.pizza.cut()
      this.pizza.box()
    } while (true)
  }
}
The advantages and disadvantages of the traditional way
  1. The advantage is relatively easy to understand, easy to operate.
  2. The disadvantage is a violation of design patterns ocp 原则, that is 对扩展开放, 对修改关闭. That is, when we add new features to the class, try not to modify the code, modify the code or less as possible.
  3. For example, we then want to add a new species Pizza (Cheese pizza), we need to make changes in extra
Simple Factory example:

The 生产对象logic 抽象到一个类of, 解耦, 代码重用性高:

object SimpleFactory {

  //提供了一个创建Pizza的方法,有需要创建Pizza调用该方法即可
  def createPizza(t: String): Pizza = {
    var pizza: Pizza = null
    if (t.equals("greek")) {
      pizza = new GreekPizza
    } else if (t.equals("pepper")) {
      pizza = new PepperPizza
    } else if (t.equals("cheese")) {
      pizza = new CheesePizza
    }
    return pizza
  }

}
External call:
class OrderPizza {

  var orderType: String = _
  var pizza: Pizza = _
  breakable {
    do {
      println("请输入pizza的类型 使用简单工厂模式~~")
      orderType = StdIn.readLine()
      pizza = SimpleFactory.createPizza(orderType)
      if (pizza == null) {
        break()
      }
      this.pizza.prepare()
      this.pizza.bake()
      this.pizza.cut()
      this.pizza.box()
    } while (true)
  }
}
Published 125 original articles · won praise 238 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_33709508/article/details/103535750