3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

この記事は何

デザインパターンについて、Rubyでどのような使い方ができるかをまとめた記事です。
デザインパターン自体の解説は詳しく行いません。

AbstractFactoryパターンとは

AbstractFactoryパターンとは、 インターフェースによって関連するまたは依存しあうオブジェクトのファミリーを、具体的なクラスを指定せずに生成するためのパターンです。

詳しくはこちらをご覧ください。

Rubyでのコード例

以下は、RubyでAbstractFactoryパターンを実装する例です。
インターフェースをmoduleを使って実装しています。

module AbstractProductA
  def useful_function_a
    raise NotImplementedError
  end
end

class ConcreteProductA1
  include AbstractProductA
  
  def useful_function_a
    'The result of the product A1.'
  end
end

class ConcreteProductA2
  include AbstractProductA
  def useful_function_a
    'The result of the product A2.'
  end
end

module AbstractProductB
  def useful_function_b
    raise NotImplementedError
  end
end

class ConcreteProductB1
  include AbstractProductB
  def useful_function_b
    'The result of the product B1.'
  end
end

class ConcreteProductB2
  include AbstractProductB
  def useful_function_b
    'The result of the product B2.'
  end
end

module AbstractFactory
  def create_product_a
    raise NotImplementedError
  end

  def create_product_b
    raise NotImplementedError
  end
end

class ConcreteFactory1
  include AbstractFactory

  def create_product_a
    ConcreteProductA1.new
  end

  def create_product_b
    ConcreteProductB1.new
  end
end

class ConcreteFactory2
  include AbstractFactory

  def create_product_a
    ConcreteProductA2.new
  end

  def create_product_b
    ConcreteProductB2.new
  end
end

def execution(factory)
  product_a = factory.create_product_a
  product_b = factory.create_product_b

  puts product_a.useful_function_a
  puts product_b.useful_function_b
end

execution(ConcreteFactory1.new)
execution(ConcreteFactory2.new)
実行結果
The result of the product A1.
The result of the product B1.
The result of the product A2.
The result of the product B2.
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?