定义
简单工厂模式属于创建型模式,又叫做静态工厂方法模式。是一个由工厂对象来决定创建哪一种产品类型的实例。简单来说就是通过传入不同的类型,来决定具体创建那个类型的实例,这些实例都有一个共同的特性,那就是具有公共的抽象父类。
UML类图
简单工厂模式实现
声明抽象类
class Operation {
private var numberA: Double = 0
private var numberB: Double = 0
var NumberA: Double {
get {
numberA
}
set {
numberA = newValue
}
}
var NumberB: Double {
get {
numberB
}
set {
numberB = newValue
}
}
func getResult() ->Double {
let result: Double = 0
return result
}
}
声明具体的操作类
具体的操作类,继承自抽象类。拥有抽象类中的所有属性和方法。
class Addition: Operation {
override func getResult() ->Double {
var result: Double = 0
result = NumberA + NumberB
return result
}
}
class Subtraction: Operation {
override func getResult() -> Double {
var reslut: Double = 0
reslut = NumberA - NumberB
return reslut
}
}
class Multiplication: Operation {
override func getResult() -> Double {
var result: Double = 0
result = NumberA * NumberB
return result
}
}
class Division: Operation {
override func getResult() -> Double {
var result: Double = 0
if NumberB != 0 {
result = NumberA / NumberB
} else {
print("除数不能为0")
}
return result
}
}
声明简单工厂类
简单工厂类用来创建具体的实例子类,根据传入的不同类型来创建具体的实例。
enum Operator {
case addition
case subtraction
case multiplication
case division
}
class OperationFactory {
static func operation(_ operation: Operator) -> Operation {
var operatorObj: Operation
switch operation {
case .addition:
operatorObj = Addition()
case .subtraction:
operatorObj = Subtraction()
case .multiplication:
operatorObj = Multiplication()
case .division:
operatorObj = Division()
}
return operatorObj
}
}
简单工厂类的具体使用
let option: Operation = OperationFactory.operation(.addition)
option.NumberA = 1
option.NumberB = 3
print(option.getResult())