Created
August 12, 2015 13:52
-
-
Save thiagofm/b31dbaf6bc1773bc0a2c to your computer and use it in GitHub Desktop.
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 Command | |
attr_reader :result | |
def initialize(result) | |
@result = result | |
end | |
def execute | |
end | |
end | |
class CompositeCommand < Command | |
def initialize(result) | |
@commands = [] | |
@result = result | |
end | |
def add_commmand command | |
@commands.push command | |
end | |
def execute | |
@commands.each {|command| @result = command.execute(@result) } | |
end | |
end | |
class MultiplyRule < Command | |
def initialize(multiplier) | |
@multiplier = multiplier | |
super | |
end | |
def execute(result) | |
result * @multiplier | |
end | |
end | |
class SumRule < Command | |
def initialize(sum) | |
@sum = sum | |
super | |
end | |
def execute(result) | |
result + @sum | |
end | |
end | |
cmd = CompositeCommand.new 1 | |
cmd.add_commmand MultiplyRule.new 1 # 1*1=1 | |
cmd.add_commmand SumRule.new 2 # 1+2=3 | |
cmd.add_commmand MultiplyRule.new 3 # 3*3=9 | |
cmd.add_commmand SumRule.new 2 # 9+2=11 | |
cmd.execute | |
p cmd.result # ~> 11 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment