jeudi 20 avril 2017

Command Pattern in Ruby

I like Ruby and I'm learning design patterns. Here is an example of Command Pattern. The domain model is as follows:

  • Command - generic interface for all command
  • OnCommand, OffCommand - particular command implementing Command interface
  • Button - uses Command objects to get result
  • RemoteContol - client, initializes Button and Command objects Button - uses Command objects to execute command
  • TV - receives the commands

Here is some code for this issue:

class TV
  def on
    puts 'TV is on'
  end

  def off
    puts 'TV is off'
  end
end

class Command
  class Error < StandardError; end

  def execute
    raise Error
  end
end

class OnCommand < Command
  attr_reader :tv

  def initialize(tv)
    @tv = tv
  end

  def execute
    tv.on
  end
end

class OffCommand < Command
  attr_reader :tv

  def initialize(tv)
    @tv = tv
  end

  def execute
    tv.off
  end
end

class Button
  attr_reader :command

  def initialize(command)
    @command = command
  end

  def execute_command
    command.execute
  end
end

class RemoteControl
  attr_reader :tv

  def initialize(tv)
    @tv = tv
    @buttons = {
      on: Button.new(OnCommand.new(tv)),
      off: Button.new(OffCommand.new(tv))
    }
  end

  def use_button(name)
    button(name).execute_command
  end

  private

  def button(name)
    @buttons.fetch name
  end
end

Here is usage example:

tv = TV.new                                                                                                             
remote_control = RemoteControl.new(tv)                                                                                  
remote_control.use_button(:on) # TV is on                                                                                         
remote_control.use_button(:off) # TV is off 

How good have I understood Command Pattern? Is it a good example?

Any thoughts are appreciated

Aucun commentaire:

Enregistrer un commentaire