RussOlsenStrategyMethod

template55.rb 元のやつ

  def initialize
    @title = '月次報告'
    @text = ['順調','さいこ〜〜〜']
  end
  
  def output_report
    puts '<html>'
    puts ' <head>'
    puts ' <meta charset="UTF-8">'
    puts " <title>#{@title}</title>"
    puts ' </head>'
    puts ' <body>'
    @text.each{|line|
      puts(" <p>#{line}</p>")
    }
    puts ' </body>'
    puts '</html>'
  end
end

report = Report.new
report.output_report

strategy72.rb HTMLだけ

class Report
  attr_reader :title, :text
  attr_accessor :formatter

  def initialize(formatter)
    @title = '月次報告'
    @text = ['順調','さいこ〜〜〜']
    @fomatter = formatter
  end

  def output_report
    @fomatter.output_report(@title, @text)
  end
end

class Formatter
  def output_report(title,text)
    raise 'Abstract method called.'
  end
end

class HTMLFormatter < Formatter
  def output_report(title,text)
    puts '<html>'
    puts ' <head>'
    puts ' <meta charset="UTF-8">'
    puts " <title>#{title}</title>"
    puts ' </head>'
    puts ' <body>'
    text.each{|line|
      puts(" <p>#{line}</p>")
    }
    puts ' </body>'
    puts '</html>'
  end
end

report = Report.new(HTMLFormatter.new)
report.output_report

strategy72-1.rb Raiseも含めて

strategy76.rb 基底クラスを削除


class Report
  attr_reader :title, :text
  attr_accessor :formatter

  def initialize(formatter)
    @title = '月次報告'
    @text = ['順調','さいこ〜〜〜']
    @fomatter = formatter
  end

  def output_report
    @fomatter.output_report(self)
  end
end

class HTMLFormatter
  def output_report(context)
    puts '<html>'
    puts ' <head>'
    puts ' <meta charset="UTF-8">'
    puts " <title>#{context.title}</title>"
    puts ' </head>'
    puts ' <body>'
    context.text.each{|line|
      puts(" <p>#{line}</p>")
    }
    puts ' </body>'
    puts '</html>'
  end
end

class PlainTextFormatter
  def output_report(context)
    puts " ***#{context.title}***"
    context.text.each{|line|
      puts(" #{line}\n")
    }
  end
end

report = Report.new(HTMLFormatter.new)
report.output_report

report = Report.new(PlainTextFormatter.new)
report.output_report

strategy82.rb さらにclassもいらない...

class Report
  attr_reader :title, :text
  attr_accessor :formatter

  def initialize(&formatter)
    @title = '月次報告'
    @text = ['順調','さいこ〜〜〜']
    @formatter = formatter
  end

  def output_report
    @formatter.call( self )
  end
end

HTMLFormatter = lambda do |context|
    puts '<html>'
    puts ' <head>'
    puts ' <meta charset="UTF-8">'
    puts " <title>#{context.title}</title>"
    puts ' </head>'
    puts ' <body>'
    context.text.each{|line|
      puts(" <p>#{line}</p>")
    }
    puts ' </body>'
    puts '</html>'
end

report = Report.new &HTMLFormatter
report.output_report

#report = Report.new &PlainTextFormatter
report2 = Report.new do|context|
    puts " ***#{context.title}***"
    context.text.each{|line|
      puts(" #{line}\n")
   }
end

report2.output_report
Last modified:2016/07/19 12:42:27
Keyword(s):
References: