工厂方法
2017-09-25 本文已影响6人
863cda997e42
🏭 Factory Method
The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.(使用工厂模式取代类构造函数,抽象对象生成过程,对象实例化的类型可以在运行时决定。)
/*:
### Example
*/
protocol Currency {
func symbol() -> String
func code() -> String
}
class Euro : Currency {
func symbol() -> String {
return "€"
}
func code() -> String {
return "EUR"
}
}
class UnitedStatesDolar : Currency {
func symbol() -> String {
return "$"
}
func code() -> String {
return "USD"
}
}
enum Country {
case unitedStates, spain, uk, greece
}
enum CurrencyFactory {
static func currency(for country:Country) -> Currency? {
switch country {
case .spain, .greece :
return Euro()
case .unitedStates :
return UnitedStatesDolar()
default:
return nil
}
}
}
/*:
### Usage
*/
let noCurrencyCode = "No Currency Code Available"
CurrencyFactory.currency(for: .greece)?.code() ?? noCurrencyCode
CurrencyFactory.currency(for: .spain)?.code() ?? noCurrencyCode
CurrencyFactory.currency(for: .unitedStates)?.code() ?? noCurrencyCode
CurrencyFactory.currency(for: .uk)?.code() ?? noCurrencyCode