Design patterns 23 of the abstract factory pattern

The first two blog 简单工厂and 工厂方法Pizza examples, they have their own drawbacks, for example, or不够解耦

The introduction of the abstract factory pattern:

  1. Abstract factory pattern: the definition of a trait for creating dependency or related cluster of objects, without having to specify a specific class
  2. Abstract factory pattern can be simple factory pattern and factory method pattern integration.
  3. From the design perspective, the abstract factory pattern is simple factory pattern of improvement (or called for further abstraction).
  4. The abstract factory into two layers, AbsFactory (abstract factory) and plant specific implementation subclasses. Programmers can use the corresponding sub-class factory to create objects according to the type. This will become a single simple factory class factory cluster, more conducive to the maintenance and expansion of the code.

Abstract plant trait (for example language Scala, traitcan be seen as the Java version 抽象类和接口的合体)

trait AbsFactory {
  //一个抽象方法
  def  createPizza(t : String ): Pizza
}

achieve工厂子类

//这时一个实现了AbsFacotory的一个子工厂类
//如果我们希望订购北京的Pizza就使用该工厂子类
class BJFactory extends AbsFactory {
  override def createPizza(t: String): Pizza = {
    var pizza: Pizza = null
    if (t.equals("cheese")) {
      pizza = new BJCheesePizza
    } else if (t.equals("pepper")) {
      pizza = new BJPepperPizza
    }
    return pizza
  }
}

Callback Interface full use polymorphism

//OrderPizza ,当我们使用抽象工厂模式后,我们订购一个Pizza思路
//1.接收一个子工厂实例,根据该工厂的创建要求去实例
class OrderPizza {

  var absFactory: AbsFactory = _  // _代表默认值 但是必须声明类型让编译器知道

  def this(absFactory: AbsFactory) {
    //多态
    this
    breakable {
      var orderType: String = null
      var pizza: Pizza = null
      do {
        println("请输入pizza的类型 ,使用抽象工厂模式...")
        orderType = StdIn.readLine()
        //使用简单工厂模式来创建对象.
        pizza = absFactory.createPizza(orderType)
        if (pizza == null) {
          break()
        }
        pizza.prepare()
        pizza.bake()
        pizza.cut()
        pizza.box()
      } while (true)
    }
  }
}

Beijing still want to eat specifically to see London incoming抽象工厂实现类

Specific want to eat pizza broken down as it depends on the type of console input

orderType = StdIn.readLine()

object PizzaStore {
  def main(args: Array[String]): Unit = {
    new OrderPizza(new BJFactory)  //
    //new OrderPizza(new LDFactory)
  }
}
Published 125 original articles · won praise 238 · views 20000 +

Guess you like

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