🐙

ストラテジーパターンのこと始め

2023/11/01に公開

概要

ストラテジーパターンについて実例を記載する。

題材

文字列を装飾する実装をストラテジーパターンを用いて実現する。

実例

# frozen_string_literal: true

class RawText
  def initialize(text, formatter)
    @text = text
    @formatter = formatter
  end

  def output
    @formatter.output(@text)
  end
end

class BaseFormatter
  def output(_text)
    raise 'output関数を定義する必要があります。'
  end
end

class AsteriskFormatter < BaseFormatter
  def output(text)
    puts "*#{text}*"
  end
end

class ExclamationMarkFormatter < BaseFormatter
  def output(text)
    puts "!#{text}!"
  end
end

raw_text_with_asterisk = RawText.new('六義園', AsteriskFormatter.new)
raw_text_with_asterisk.output

raw_text_with_exclamation_mark = RawText.new('六義園', ExclamationMarkFormatter.new)
raw_text_with_exclamation_mark.output

実行結果は、次の通りです。

russ@penguin:~$ ruby strategy.rb 
*六義園*
!六義園!

Discussion