0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swiftでデザインパターン【Factory Method】

Posted at

元ネタ → ochococo/Design-Patterns-In-Swift

クラス図

image.png

図の引用元: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を識別しているという意味で。

考察

ConcreteProductCurrencyDescriptionプロトコルに準拠させている。CurrencyFactorycurrency()では、戻り値をCurrencyDescriptionにしておくことで(アップキャスト)、実行時にenumのcaseで、具体的なConcreteProductを判別・生成できるようになっている(ポリモーフィズム)。
Java等のサンプルでは、CreatoranOperation()のなかで、ConcreteCreatorで実装されたfactoryMethod()が呼ばれていることが多い。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?