Created
July 26, 2014 03:13
-
-
Save kasei-san/e9d0387e19b59ea53ffa to your computer and use it in GitHub Desktop.
Strategy パターン ref: http://qiita.com/kasei-san/items/91ab181443df03da0343
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
アルゴリズムを実行時に選択することができるデザインパターンである。 |
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
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