LoginSignup
3
1

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-03-03

概要

互いに関連するオブジェクト群を生成するための抽象化されたインターフェイスをクライアントに提供するパターン

以下の4種類のクラスからなる
1. Abstract Factoryクラス(関連するオブジェクト群を生成するためのインターフェイスを宣言)
2. Concrete Factoryクラス(関連するオブジェクト群の生成を実装する)
3. Abstract Productクラス(個々のオブジェクトを生成するためのインターフェイスを宣言)
4. Concrete Productクラス(個々のオブジェクトの生成を実装する)

具体例と実装

乗り物工場を例にすると、

上記1~4はそれぞれ

  1. 乗り物工場クラス(VehicleFacrtoryクラス)
  2. 自動車工場クラス、自転車工場クラス(CarFactoryクラス、BicyclFactoryクラス)
  3. タイヤクラス、車体クラス(Wheelクラス、Bodyクラス)
  4. 自転車用タイヤクラス、車用タイヤクラス、自転車車体クラス、車車体クラス(CarWheel,BicycleWheel,CarBody,BicycleBodyクラス)

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

vehicle_factory.rb
class VehicleFacrtory
  def create_vehicle
    create_body
    create_wheel
  end

  private

  def create_body
  end

  def create_wheel
  end
end
car_factory.rb
class CarFactory < VehicleFacrtory
  def create_body
    return CarBody.new
  end

  def create_wheel
    return CarWheel.new
  end
end
bicycle_factory.rb
class BicyclFactory < VehicleFacrtory
  def create_body
    return BicycleBody.new
  end

  def create_wheel
    return BicycleWheel.new
  end
end
end
body.rb
class Body
  def initialize
  end
end
wheel.rb
class Wheel
  def initialize
  end
end
car_body.rb
class CarBody
  def initialize
  end
end
car_wheel.rb
class CarWheel
  def initialize
  end
end
bicycle_body.rb
class BicycleBody
  def initialize
  end
end
bicycle_wheel.rb
class BicycleWheel
  def initialize
  end
end

クライアントコード

client.rb
car_factory = CarFactory.new()
car = car_factory.create_vehicle

bicycle_factory = BicycleFactory.new()
bicycle = bicycle_factory.create_vehicle

メリット

  • 作成するオブジェクトを入れ替えるのが容易
  • オブジェクト間の無矛盾性を担保できる

まとめ

利用するオブジェクトの整合性を保ちたいときに便利なパターン

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