LoginSignup
3
1

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-06-28

概要

オブジェクトの生成をサブクラスに委譲するパターン

以下の4種類のクラスからなる
1. Productクラス(生成するオブジェクトのインターフェイスを定義)
2. Concrete Productクラス(1.のクラスのインターフェイスを実装)
3. Creatorクラス(オブジェクトを生成するためのfactory methodを定義)
4. ConcreteCreatorクラス(2.のインスタンスを返すようにfactory methodをオーバーライドする)

具体例と実装

スピーカーを例にすると

上記1~4はそれぞれ
1. スピーカークラス
2. アナログスピーカークラス、デジタルスピーカークラス
3. スピーカー製造クラス
4. アナログスピーカー製造クラス、デジタルスピーカー製造クラス

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

speaker.rb
class Speaker
  def play(source)
    fail NotImplementedError
  end
end
digital_speaker.rb
class DigitalSpeaker < Speaker
  def play(source)
    # 音源をデジタル出力
  end
end
analog_speaker.rb
class AnalogSpeaker < Speaker
  def play(source)
    # 音源をアナログ出力
  end
end
speaker_creator.rb
class SpeakerCreator
  def initialize
  end

  def speaker
    fail NotImplementedError
  end
end
digital_speaker_creator.rb
class DigialSpeakerCreator < SpeakerCreator
  def speaker
    DigitalSpeaker.new
  end
end
analog_speaker_creator.rb
class AnalogSpeakerCreator < SpeakerCreator
  def speaker
    AnalogSpeaker.new
  end
end

メリット

  • オブジェクトの使用者がオブジェクトの生成過程を知る必要がなくなる
  • template methodパターンと組み合わせることでDRYなコードが書ける

まとめ

生成しなければならないオブジェクトのクラスを事前に知ることができない場合に利用するパターン

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