この記事は何
デザインパターンについて、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.