Command Pattern in Ruby
-
Upload
jyaasa-technologies -
Category
Technology
-
view
277 -
download
0
Transcript of Command Pattern in Ruby
Hello ! I am Nelson Suwal
http://jyaasa.comCopyright 2016. Jyaasa Technologies.
Apprentice
Jyaasa Technologies
What is Command Pattern? The command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time.
Four terms always associated with the command pattern:
● Command● Receiver● Invoker● Client
http://jyaasa.comCopyright 2016. Jyaasa Technologies.
# Invokerclass Switch attr_reader :history
def execute(cmd) @history ||= [] @history << cmd.execute endend
# Command Interfaceclass Command attr_reader :light
def initialize(light) @light = light end def execute raise NotImplementedError endend
http://jyaasa.comCopyright 2016. Jyaasa Technologies.
# Command for turning onclass TurnOnCommand < Command def execute light.turn_on endend
# Command for turning offclass TurnOffCommand < Command def execute light.turn_off endend
# Receiverclass Light def turn_on 'the light is on' end
def turn_off 'the light is off' endend
http://jyaasa.comCopyright 2016. Jyaasa Technologies.
# Clientclass LightSwitchClient attr_reader :switch
def initialize @lamp = Light.new @switch = Switch.new end
def switch_for(cmd) case cmd when 'on' then @switch.execute(TurnOnCommand.new(@lamp)) when 'off' then @switch.execute(TurnOffCommand.new(@lamp)) else puts 'Sorry, I so sorry' end endend
http://jyaasa.comCopyright 2016. Jyaasa Technologies.
client = LightSwitchClient.newputs client.switch_for('on') puts client.switch_for('off')puts client.switch.history
#output :'the light is on'#output :'the light is off'#output :['the light is on',the light is off']
http://jyaasa.comCopyright 2016. Jyaasa Technologies.
Resources:
● https://en.wikipedia.org/wiki/Command_pattern● https://sourcemaking.com/design_patterns/command● http://www.oodesign.com/command-pattern.html
http://jyaasa.comCopyright 2016. Jyaasa Technologies.