Created
March 30, 2020 01:30
-
-
Save yowchun93/7ec7b0645214065cbe1fa8547c55c4fb 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
class TextParser | |
attr_reader :text, :parser | |
def initialize(text, parser) | |
@text = text | |
@parser = parser | |
end | |
def call | |
parser.call(text) | |
end | |
end | |
class XMLParser | |
def call(text) | |
"<text>#{text}</text>" | |
end | |
end | |
class JSONParser | |
def call(text) | |
"{ text: #{text} }" | |
end | |
end | |
puts TextParser.new('My Text', XMLParser.new).call | |
puts TextParser.new('My Text', JSONParser.new).call | |
# -> (text) { text.reverse } is a reference to a lambda. This demonstrates | |
# the power of functional programming. | |
puts TextParser.new('My Text', -> (text) { text.reverse }).call |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment