抽象工廠模式屬于創(chuàng)建型模式。抽象工廠就是工廠的工廠,目的是使工廠也能按需動態(tài)創(chuàng)建。
示例代碼
protocol Decimal {
func stringValue() -> String
// factory
static func make(string : String) -> Decimal
}
typealias NumberFactory = (String) -> Decimal
// Number implementations with factory methods
struct NextStepNumber : Decimal {
private var nextStepNumber : NSNumber
func stringValue() -> String { return nextStepNumber.stringValue }
// factory
static func make(string : String) -> Decimal {
return NextStepNumber(nextStepNumber:NSNumber(value:(string as NSString).longLongValue))
}
}
struct SwiftNumber : Decimal {
private var swiftInt : Int
func stringValue() -> String { return "\(swiftInt)" }
// factory
static func make(string : String) -> Decimal {
return SwiftNumber(swiftInt:(string as NSString).integerValue)
}
}
Abstract factory:
enum NumberType {
case NextStep, Swift
}
enum NumberHelper {
static func factoryFor(type : NumberType) -> NumberFactory {
switch type {
case .NextStep:
return NextStepNumber.make
case .Swift:
return SwiftNumber.make
}
}
}
使用方式
let factoryOne = NumberHelper.factoryFor(type: .NextStep)
let numberOne = factoryOne("1")
numberOne.stringValue()
let factoryTwo = NumberHelper.factoryFor(type: .Swift)
let numberTwo = factoryTwo("2")
numberTwo.stringValue()
理解
還是從使用的角度來理解:
- 「工廠模式」
- 工廠類實例化所需對
- 使用對象
- 「抽象工廠模式」
- 抽象工廠類創(chuàng)建所需工廠
- 工廠實例化所需對象
- 使用對象
抽象工廠其實就是個生產(chǎn)工廠的工廠,進行了兩層業(yè)務封裝。
目前還沒用過這個模式,學習了這個模式后以后看到類似的業(yè)務需求可以使用這個模式來實現(xiàn)。
知道了并不一定要用,但要用的時候一定要知道。