Created
November 4, 2012 09:00
-
-
Save ackintosh/4010809 to your computer and use it in GitHub Desktop.
Strategy Pattern in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Formatter | |
def output_report(title, text) | |
raise 'Called abstract method !!' | |
end | |
end | |
class HTMLFormatter < Formatter | |
def output_report(report) | |
puts "<html><head><title>#{report.title}</title></head>" | |
puts '<body>' | |
report.text.each do |line| | |
puts "<p>#{line}</p>" | |
end | |
puts '</body></html>' | |
end | |
end | |
class PlainTextFormatter < Formatter | |
def output_report(report) | |
puts "*** #{report.title} ***" | |
report.text.each do |line| | |
puts(line) | |
end | |
end | |
end | |
class Report | |
attr_reader :title, :text | |
attr_accessor :formatter | |
def initialize(formatter) | |
@title = 'report title' | |
@text = ['text1', 'text2', 'text3'] | |
@formatter = formatter | |
end | |
def output_report | |
@formatter.output_report(self) | |
end | |
end | |
report = Report.new(HTMLFormatter.new) | |
report.output_report | |
# <html><head><title>report title</title></head> | |
# <body> | |
# <p>text1</p> | |
# <p>text2</p> | |
# <p>text3</p> | |
# </body></html> | |
report.formatter = PlainTextFormatter.new | |
report.output_report | |
# *** report title *** | |
# text1 | |
# text2 | |
# text3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment