The abstract factory pattern is used to provide a client with a set of related or dependant objects. The "family" of objects created by the factory are determined at run-time.(使用抽象工厂模式为客户提供一组相关或依赖对象。创建的对象工厂是在运行时决定的。)
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 factory(for type: NumberType) -> NumberFactory {
switch type {
case .nextStep:
return NextStepNumber.make
case .swift:
return SwiftNumber.make
}
}
}
/*:
### Usage
*/
let factoryOne = NumberHelper.factory(for: .nextStep)
let numberOne = factoryOne("1")
numberOne.stringValue()
let factoryTwo = NumberHelper.factory(for: .swift)
let numberTwo = factoryTwo("2")
numberTwo.stringValue()
网友评论