什么是工厂办法?

界说一个用于创建目标的接口,让子类决议实例化哪一个类,工厂办法使一个类的实例化延迟到其子类

结构图

classDiagram
Product <|.. ConcreteProduct
class Product{
<<interface>>
}
class ConcreteProduct{
<<详细的产品,实现Product接口>>
}
Creator <|-- ConcreteCreator
ConcreteCreator ..> ConcreteProduct
class Creator{
+FactoryMethod() 声明工厂办法,回来一个 Product 类型的目标
}
class ConcreteCreator{
+FactoryMethod() 重界说工厂办法回来一个 ConcreteProduct 类型的目标
}

实例

实现一个计算器,拥有加减乘除功能:

1.笼统一个protocol(Operation), 即:对应结构图中的Product接口。

protocol Operation {
  var numberA: Double { set get }
  var numberB: Double { setget }
 
  func calculate() -> Double
}

2.笼统一个protocol(OperationFactory),即:对应结构图中的Creator。协议里边有一个创建Operation类型的目标。

protocol OperationFactory {
  func creatOperation() -> Operation
}

3.界说详细的加减乘除的详细Operation目标,都需求实现Operation协议。

struct OperationAdd: Operation {
  var numberA: Double = 0.0
  var numberB: Double = 0.0
  func calculate() -> Double {
    return numberA + numberB
  }
}
struct OperationSub: Operation {
  var numberA: Double = 0.0
  var numberB: Double = 0.0
  func calculate() -> Double {
    return numberA - numberB
  }
}
struct OperationMul: Operation {
  var numberA: Double = 0.0
  var numberB: Double = 0.0
  func calculate() -> Double {
    return numberA * numberB
  }
}
struct OperationDiv: Operation {
  var numberA: Double = 0.0
  var numberB: Double = 0.0
  func calculate() -> Double {
    if numberB != 0 {
      return numberA / numberB
    }
    return 0
  }
}

4.界说详细工厂类。


class OperationAddFactory: OperationFactory {
  func creatOperation() -> Operation {
    return OperationAdd()
  }
}
class OperationSubFactory: OperationFactory {
  func creatOperation() -> Operation {
    return OperationSub()
  }
}
class OperationMulFactory: OperationFactory {
  func creatOperation() -> Operation {
    return OperationMul()
  }
}
class OperationDivFactory: OperationFactory {
  func creatOperation() -> Operation {
    return OperationDiv()
  }
}
/// 客户端调用
 let addFactory = OperationAddFactory()
 var addOperation = addFactory.creatOperation()
 addOperation.numberA = 1
 addOperation.numberB = 2
 addOperation.calculate()
 let subFactory = OperationSubFactory()
 var subOperation = subFactory.creatOperation()
 subOperation.numberA = 1
 subOperation.numberB = 2
 subOperation.calculate()
 let mulFactory = OperationMulFactory()
 var mulOperation = mulFactory.creatOperation()
 mulOperation.numberA = 1
 mulOperation.numberB = 2
 mulOperation.calculate()
 let divFactory = OperationDivFactory()
 var divOperation = divFactory.creatOperation()
 divOperation.numberA = 1
 divOperation.numberB = 2
 divOperation.calculate()

工厂形式总结

  • 工厂办法形式实现时,客户端需求决议实例化哪一个工厂来实现详细的运算类,与简略工厂相比较,其实选择判别问题仍是存在,也就是说,工厂办法把简略工厂的内部逻辑判别移到了客户端代码进行。
  • 契合开闭准则。假设现在有需求需求添加一个开根号的运算,那么只需求添加一个该运算的详细工厂类和运算类。
  • 工厂办法形式需求引进许多新的子类,代码可能会因而变得更复杂。