LoginSignup
2
3

More than 3 years have passed since last update.

[備忘録]Swiftでのstrategyパターン

Last updated at Posted at 2021-04-02

SwiftでGofのデザインパターンstrategyの備忘録

忘れそうだったのでメモ

// タイプコード
enum Type {
    case A, B, C
}

func execute(type: Type) {
    strategyForType(type: 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が呼ばれる")
    }
}

語彙説明

タイプコード

オブジェクトの種別を表す値のこと
交通手段として、徒歩/電車/タクシーがあった場合

徒歩...0
電車...1
タクシー...2

このときの0,1,2がタイプコード

2
3
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
2
3