Last active
August 29, 2015 14:16
-
-
Save geckofu/1f7a17681c0051506a14 to your computer and use it in GitHub Desktop.
strategy pattern
This file contains hidden or 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
# the user of the strategy -- called the context class -- | |
# can treat the strategies like interchangeable parts. | |
# In addition, because the strategy pattern is based on composition | |
# and delegation, rather than on inheritance, it is easy to switch strategies | |
# at runtime. | |
class PlainTextFormatter | |
def output_report(title, text) | |
puts("**** #{title} ****") | |
text.each do |line| | |
puts(line) | |
end | |
end | |
end | |
class Report | |
attr_reader :title, :text | |
attr_accessor :formatter | |
def initialize(formatter) | |
@title = 'Monthly Report' | |
@text = ['Things are going', 'really, really well.'] | |
@formatter = formatter | |
end | |
def output_report | |
@formatter.output_report(@title, @text) | |
end | |
end | |
report = Report.new(PlainTextFormatter.new) | |
report.output_report | |
report.formatter = HTMLFormatter.new | |
report.output_report | |
# Optional way to share data between the Context and the Strategy: | |
# Pass a reference of the context to the strategy | |
# disadvantage: it increases the coupling between the context and the strategy. | |
class Report | |
*** | |
def output_report | |
@formatter.output_report(self) | |
end | |
end | |
class HTMLFormatter | |
def output_report(context) | |
*** | |
puts("<title>#{context.title}</title>") | |
end | |
end | |
# Strategy Pattern the Proc way: | |
class Report | |
*** | |
def initialize(&formatter) | |
@title = 'Monthly Report' | |
@text = ['Things are going', 'really, really well.'] | |
@formatter = formatter | |
end | |
def output_report | |
@formatter.call(self) | |
end | |
end | |
HTML_FORMATTER = lambda do |context| | |
*** | |
puts("<title>#{context.title}</title>") | |
end | |
report = Report.new(&HTML_FORMATTER) | |
# build the formatter on-the-fly | |
# suitable for one-method strategy | |
report = Reprot.new do |context| | |
puts("**** #{context.title} ****") | |
end | |
# another Proc strategy example is the sort method | |
array.sort | |
array.sort {|a,b| a.length <=> b.length} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment