Skip to content

Instantly share code, notes, and snippets.

@kasei-san
Created July 26, 2014 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kasei-san/e9d0387e19b59ea53ffa to your computer and use it in GitHub Desktop.
Save kasei-san/e9d0387e19b59ea53ffa to your computer and use it in GitHub Desktop.
アルゴリズムを実行時に選択することができるデザインパターンである。
class StringLister
attr_reader :items
def initialize(items, &strategy)
@items = items
@strategy = strategy
end
def display
@strategy.call(@items)
end
end
items = %w[abc def ghi]
disp = StringLister.new(items) do |items|
result = []
result << "<html><body>"
items.each{|item| result << "<div>#{item}</div>" }
result << "</body></html>"
result.join("\n")
end.display
puts disp
# <html><body>
# <div>abc</div>
# <div>def</div>
# <div>ghi</div>
# </body></html>
disp = StringLister.new(items) do |items|
items.join("\n")
end.display
puts disp
# abc
# def
# ghi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment