LoginSignup
1
0

More than 1 year has passed since last update.

【Ruby】みんな理解出来てる?テンプレートメソッドパターンのこと。

Posted at

テンプレートメソッドパターンとは?

テンプレートメソッドパターンはGoFのデザインパターンの一種です。

このパターンは、基底クラスに不変の部分を記述し、変わる部分はサブクラスに定義するメソッドにカプセル化するというモノです。
変わるものと変わらないものを分離するという設計の考えに基づいています。

つまり次の2つのオブジェクトによって構成されます。

- 骨格となる「抽象的な基底クラス」
- 実際の処理を行う「サブクラス」

メリット

  • 基底クラス側に、「不変の基本的なアルゴリズム」を配置可能になる。
    • 「高レベルの処理を制御すること」に集中できる。
  • サブクラス側に、「変化するロジック」を置ける
    • 「詳細を埋めること」に集中できる
  • 似通った部分を共通化して「サブクラスに対してスーパクラスで実装されている抽象メソッドを実装する」という責任を与えることが可能になる。

実装例

基底クラス

class Test
  def open()
    raise NotImplementedError.new("#{self.class}##{__method__}")
  end

  def close()
    raise NotImplementedError.new("#{self.class}##{__method__}")
  end

  def output()
    raise NotImplementedError.new("#{self.class}##{__method__}")
  end

  def display
    open()
      5.times do
        output()
      end
    close()
  end
end

サブクラス

class SubTest < Test
  def initialize(string)
    @string = string
  end

  def open
    print 'open!'
  end

  def close
    print 'close!'
  end

  def output
    print @string
  end
end

実行例

sub_test = SubTest.new('テスト')

sub_test.display
#=> open!
#=> "テスト"
#=> "テスト"
#=> "テスト"
#=> "テスト"
#=> "テスト"
#=> close!
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