5
5

More than 5 years have passed since last update.

【デザインパターン】Strategyパターン

Last updated at Posted at 2015-07-12

概要

アルゴリズムの集合を定義し、各アルゴリズムをカプセル化してそれらを交換可能にするパターン

以下の3種類のクラスからなる
1. Strategyクラス(サポートする全てのアルゴリズムに共通のインターフェイスを宣言)
2. Concrete Strategyクラス(1.で定義されたインターフェイスのアルゴリズムを実装する)
3. Contextクラス(ConcreteStrategyオブジェクトを備えている)

具体例と実装

東京〜京都の移動方法の検索を例にすると、

上記1~3はそれぞれ

  1. 移動手段検索クラス(TransitSearchクラス、東京〜京都間の移動方法検索に共通のインターフェイスを定義)
  2. 格安プラン検索クラス、最速プラン検索クラス(それぞれLowCostSearch、ShortTimeSearchクラス。それぞれ、安さ重視、早さ重視での東京〜京都間の移動手段検索を実装)
  3. 出張予約クラス(BuisinessTripReservationクラス。東京〜京都の移動方法の検索結果情報を保持)

が対応する。
コードの詳細は以下

transit_search.rb
class TransitSearch
  def search(date)
  end
end
low_cost_search.rb
class LowCostSearch < TransferSearch
  def search(date)
    # 指定日の最安移動方法を取得
  end
end
short_time_search.rb
class ShortTimeSearch < TransferSearch
  def search(date)
    # 指定日の最速移動方法を取得
  end
end
buisiness_trip.rb
class BuisinessTrip
  def initialize(transit_search)
    @transit_search = transit_search.search(#{trip_date})
  end

  def transfer_reservation
    reserve(@transit_search)
  end

  def reserve(transit_search)
    #検索結果日程を予約 
  end
end

クライアントコード

# 急ぎの出張
buisiness_trip = BuisinessTrip.new(ShortTimeSearch.new)
buisiness_trip.transfer_reservation

# 金欠出張
buisiness_trip = BuisinessTrip.new(LowCostSearch.new)
buisiness_trip.transfer_reservation

メリット

  • 関連するアルゴリズムの集合を再利用出来るよう、Strategyクラスの階層によって定義している
  • Contextオブジェクトと独立にアルゴリズムを変更出来るようになる

まとめ

関連するアルゴリズムをまとめることで、アルゴリズムと、それを利用するオブジェクトとを独立させることができるパターン

5
5
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
5
5