Skip to content

Instantly share code, notes, and snippets.

@Taishikun0721
Last active November 30, 2020 08:11
Show Gist options
  • Save Taishikun0721/734ea4a38a7bee686703fc9daca6507e to your computer and use it in GitHub Desktop.
Save Taishikun0721/734ea4a38a7bee686703fc9daca6507e to your computer and use it in GitHub Desktop.

Rubyデザインパターン Strategy Patterm

デザインパターンのひとつStrategy Pattermの例を見つけたので実行してみました! ほとんどコピペで参考サイトに書いてあるのと同じ!けど練習と知識定着の為に、一つ新しいクラスを作ってこのまとめも書きました笑

まず親クラス今回はReportクラスがあって、ここではレポートを出力するメソッドoutput_reortが存在する。 ただHTML形式で書き出したい場合と、Text形式で書き出したい場合がある。その場合if文を書いてしまうとど形式が増えるたびにどんどん条件分岐が増えてしまい 管理がかなり大変になる。

なのでレポートの形式をクラスに格納してしまって、呼び出したいときに呼び出すようにしよう!というのがストラテジーパターンの考え方。 今回は、3つの形式があります
1.HtmlFormatterクラス ※HTML形式で出力
2.PlainTextFormatterクラス ※text形式で出力
3.MixTextFormatterクラス ※合わせて出力(自分が勉強の為に作っただけ)

この3つのクラスのインスタンスをReportクラスのインスタンスに渡すだけでどの形式で使用するかを決める事が出来ます。 ちょうど@formatterに引数に渡したインスタンスが入るから、それぞれのクラスのoutput_reportを呼び出すことが出来る! おもしろいんでコピペして動かしてみて下さい!

■参考情報

  1. ストラテジ(Strategy) | Ruby デザインパターン
  2. Rubyによるデザインパターン【Strategy】-取り替え可能パーツ群を戦略的に利用せよ-
class Report
attr_reader :title, :text
attr_accessor :formatter
def initialize(formatter)
@title = '月次報告'
@text = ['最高', '順調', '普通']
@formatter = formatter
end
def output_report
@formatter.output_report(self)
end
end
class HTMLFormatter
def output_report(context)
puts('<html>')
puts(' <head>')
puts(" <title>#{context.title}</title>")
puts(' </head>')
puts(' <body>')
context.text.each do |line|
puts(" <p>#{line}</p>")
end
puts(' </body>')
puts('</html>')
end
end
class PlainTextFormatter
def output_report(context)
puts("*** #{context.title} ***")
context.text.each do |line|
puts(line)
end
end
end
class MixTextFormatter
def output_report(context)
puts('<html>')
puts(' <head>')
puts(" <title>#{context.title}</title>")
puts(' </head>')
puts(' <body>')
context.text.each do |line|
puts(line)
end
puts(' </body>')
puts('</html>')
end
end
report = Report.new(HTMLFormatter.new)
# report = Report.new(PlainTextFormatter.new)
# report = Report.new(MixTextFormatter.new)
#見たい形式でコメントアウト解除して実行したら面白い!!if文で条件分岐を書かなくていいし綺麗!
# 最後のMixTextFormatterは自分で作ってみただけです笑
p report.output_report
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment