LoginSignup
1
0

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-03-04

概要

同じ作成過程で異なる表現形式の結果を得るためのパターン。

以下の4クラスからなる
1. Builderクラス(Productオブジェクトの構成要素を生成するためのインターフェイスを定義)
2. Concrete Builderクラス(1.のインターフェイスを実装)
3. Directorクラス(1.のインターフェイスを使ってオブジェクトを生成する)
4. Productクラス(作成中の多くの構成要素からなる複合オブジェクトを表す)

具体例

家の建築を例にすると、

上記1~4はそれぞれ

  1. 建物作成クラス
  2. 一戸建て作成クラス、高層ビル作成クラス
  3. 建築家クラス
  4. 建物クラス

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

builder.rb
class Builder
  def initialize
    @building = Building.new
  end

  def build_rooms
    @building.set_rooms
  end

  def build_floors
    @building.set_floors
  end

  def build_roofs
    @building.set_roofs
  end

  def get_result
    return @building
  end
end
detached_house_builder.rb
class DetachedHouseBuilder < Builder
  def build_rooms
    # 一戸建て用の部屋を作成
  end

  def build_floors
    # 一戸建ての各フロアを作成
  end

  def build_roofs
    # 一戸建て用の屋根を作成
  end
end
tower_building_builder.rb
class TowerBuildingBuilder < Builder
  def build_rooms
    # 高層ビル用の部屋を作成
  end

  def build_floors
    # 高層ビルの各フロアを作成
  end

  def build_roofs
    # 高層ビル用の屋根を作成
  end
end
director.rb
class Director
  def initialize(builder)
   @builder = builder
  end

  def build
    @builder.build_rooms
    @builder.build_floors
    @builder.build_roofs
    @builder.get_result
  end
end
Building.rb
class Building
  def initialize
  end

  def set_rooms
  end

  def set_floors
  end

  def set_roofs
  end
end

メリット

  • DirectorはBuilderのインターフェイスだけを知っていればいいので、ConcreteBuilderが追加されてもDirectorは影響を受けない

まとめ

複合オブジェクトを段階的に生成する際に便利なパターン

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