3
0

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でどのような使い方ができるかをまとめた記事です。
デザインパターン自体の解説は詳しく行いません。

FactoryMethodパターンとは

FactoryMethodパターンとは、スーパークラスで特定のインスタンスに対しての処理のステップを実装し、サブクラスでどのインスタンスに対して処理を行うのかを指定するデザインパターンです。

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

Rubyでのコード例

スーパークラスで手続きの流れを実装し、サブクラスで手続きの処理で呼び出しているメソッドの定義と、インスタンスの定義を行います。

class SuperClass
  def factory_method
    instance = build_instance
    method1(instance)
    method2(instance)
    method3(instance)
  end

  private

  def build_instance
    fail NotImprementedError
  end

  def method1(instance)
    puts "method1: #{instance.hoge}"
  end

  def method2(instance)
    puts "method2: #{instance.hoge}"
  end

  def method3(instance)
    puts "method3: #{instance.hoge}"
  end
end

class SubClass < SuperClass
  private

  def build_instance
    SomeClass.new
  end
end

module Buildable
  def hoge
    fail NotImprementedError
  end
end

class SomeClass
  include Buildable

  def hoge
    'hoge'
  end
end

SubClass.new.factory_method
出力結果
method1: hoge
method2: hoge
method3: hoge

どのような時に使えるか

インスタンス生成→インスタンスに対して処理を行う流れを定式化したい時に有効です。
例えばデータベースクライアントの生成処理などはFactoryMethodパターンを利用することでインスタンスの生成処理を共通化することができます。

class DatabaseConnector
  def connect
    connection = create_connection
    authenticate(connection)
    setup(connection)
    connection
  end

  private

  def create_connection
    fail NotImprementedError
  end

  def authenticate(connection)
    puts "Authenticating with #{connection.credentials}"
  end

  def setup(connection)
    puts "Setting up connection for #{connection.database}"
  end
end

class MySQLConnector < DatabaseConnector
  private

  def create_connection
    MySQLConnection.new('mysql_database')
  end
end

class PostgreSQLConnector < DatabaseConnector
  private

  def create_connection
    PostgreSQLConnection.new('postgres_database')
  end
end

class MySQLConnection
  attr_reader :database, :credentials
  def initialize(database)
    @database = database
    @credentials = "MySQL Credentials"
  end
end

class PostgreSQLConnection
  attr_reader :database, :credentials
  def initialize(database)
    @database = database
    @credentials = "PostgreSQL Credentials"
  end
end

MySQLConnector.new.connect
PostgreSQLConnector.new.connect
出力結果
Authenticating with MySQL Credentials
Setting up connection for mysql_database
Authenticating with PostgreSQL Credentials
Setting up connection for postgres_database
3
0
1

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?