元ネタ → ochococo/Design-Patterns-In-Swift
クラス図
図の引用元:Wikipedia: 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.
Factory Methodパターンは、クラスコンストラクターを置き換えるために使用され、インスタンス化されたオブジェクトのタイプを実行時に判別できるように、オブジェクト生成のプロセスを抽象化する。
サンプルコード
// Product
protocol CurrencyDescribing {
var symbol: String { get }
var code: String { get }
}
// ConcreteProduct
final class Euro: CurrencyDescribing {
var symbol: String {
return "€"
}
var code: String {
return "EUR"
}
}
// ConcreteProduct
final class UnitedStatesDolar: CurrencyDescribing {
var symbol: String {
return "$"
}
var code: String {
return "USD"
}
}
// like ConcreteCreator
enum Country {
case unitedStates
case spain
case uk
case greece
}
// Creator
enum CurrencyFactory {
// factoryMethod
static func currency(for country: Country) -> CurrencyDescribing? {
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
クラス図との対応
サンプルコード | クラス図 |
---|---|
CurrencyDescribing | Product |
サンプルコード | クラス図 |
---|---|
Euro, UnitedStatesDolar | ConcreteProduct |
サンプルコード | クラス図 |
---|---|
CurrencyFactory | Creator |
currency | factoryMethod |
サンプルコード | クラス図 |
---|---|
Country | ConcreteCreator |
※ConcreteCreatorではないが、具体的なProductを識別しているという意味で。 |
考察
ConcreteProduct
はCurrencyDescription
プロトコルに準拠させている。CurrencyFactory
のcurrency()
では、戻り値をCurrencyDescription
にしておくことで(アップキャスト)、実行時にenumのcaseで、具体的なConcreteProduct
を判別・生成できるようになっている(ポリモーフィズム)。
Java等のサンプルでは、Creator
のanOperation()
のなかで、ConcreteCreator
で実装されたfactoryMethod()
が呼ばれていることが多い。