今回は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パターンを使って書き直すと下のようになります。
TypeA
・TypeB
・TypeC
だった場合の処理をそれぞれの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)
- 作者: エリックガンマ,ラルフジョンソン,リチャードヘルム,ジョンブリシディース,Erich Gamma,Ralph Johnson,Richard Helm,John Vlissides,本位田真一,吉田和樹
- 出版社/メーカー: ソフトバンククリエイティブ
- 発売日: 1999/10
- メディア: 単行本
- 購入: 21人 クリック: 711回
- この商品を含むブログ (210件) を見る