Skip to content

Instantly share code, notes, and snippets.

@geckofu
Created February 24, 2015 13:22
Show Gist options
  • Save geckofu/8e87ce232e1a2aaf49ea to your computer and use it in GitHub Desktop.
Save geckofu/8e87ce232e1a2aaf49ea to your computer and use it in GitHub Desktop.
Template Method Pattern
# Template Method Pattern relies on inheritance
class Report
def initialize
@title = 'Monthly Report'
@text = ['Things are going', 'really, really well.']
end
def output_report
output_start
output_head
@text.each do |line|
output_line(line)
end
output_end
end
def output_start
end
def output_head
raise 'Abstract method called: output_head'
end
def output_end
end
end
class HTMLReport < Report
def output_start
puts('<html>')
end
def output_head
puts('<head>')
puts("<title>#{@title}</title>")
puts('</head>')
end
def output_line(line)
puts("<p>#{line}</p>")
end
def output_end
puts('</html>')
end
end
def PlainTextReport < Report
def output_head
puts("**** #{@title} ****")
end
def output_line(line)
puts(line)
end
end
# One characteristic that the HTMLReport and PlainTextReport share is that they look fragmentary.
# Cause they do not override the key template method, output_report.
# In the Template Method pattern, the abstract base class controls the higher-level processing
# through the template method; the sub-classes simply fill in the details.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment