しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

Swiftで学ぶデザインパターン11 (Strategyパターン)

今回はStrategyパターンについて書いていきます。

デザインパターンとは

デザインパターンとはソフトウェア開発の設計方法の事です。
オブジェクト指向における再利用のためのデザインパターン』という本が出典で、全部で23種類のパターンが紹介されています。

Strategyパターンとは

Strategyパターンとは処理の中身を外部クラスに出せるデザインパターンです。
よくあるif文だらけで辛いメソッドをすっきりさせてくれます。

SwiftでのStrategyパターンの実装方法

実装をしていると下のようにcase文で分ける事があります。
今はprintだけなので良いですが、ここが数十行になると辛いです。
そういった時にStrategyパターンは使えます。

enum Type {
    case A
    case B
    case C
}

func execute(type: Type) {
    switch type {
    case .A:
        print("A")
    case .B:
        print("B")
    case .C:
        print("C")
    }
}

execute(.A)

上をStrategyパターンを使って書き直すと下のようになります。
TypeATypeBTypeCだった場合の処理をそれぞれのStrategyに移動しました。
行数は長いですがクラスごとの処理はかなりすっきりしました。

enum Type {
    case A
    case B
    case C
}

func execute(type: Type) {
    strategyForType(type).execute()
}

func strategyForType(type: Type) -> Strategy {
    switch type {
    case .A: return StrategyA()
    case .B: return StrategyB()
    case .C: return StrategyC()
    }
}

protocol Strategy {
    func execute()
}

class StrategyA: Strategy {
    func execute() {
        print("A")
    }
}

class StrategyB: Strategy {
    func execute() {
        print("B")
    }
}

class StrategyC: Strategy {
    func execute() {
        print("C")
    }
}

execute(.A)

オブジェクト指向における再利用のためのデザインパターン

オブジェクト指向における再利用のためのデザインパターン