« Back to Index

Ruby: Command Design Pattern (can allow for “undo” history feature)

View original Gist on GitHub

Ruby Command Design Pattern.rb

# Invoker
class Invoker
  def initialize
    @history = []
  end

  def record_and_execute(command)
    @history << command  # Optional
    command.execute
  end
end

# Receiver
class Light
  def turn_on
    puts 'The light is on'
  end

  def turn_off
    puts 'The light is off'
  end
end

# A command
class TurnOnCommand
  def initialize(light)
    @light = light
  end

  def execute
    @light.turn_on
  end
end

# Another command
class TurnOffCommand
  def initialize(light)
    @light = light
  end

  def execute
    @light.turn_off
  end
end

# Client
class Client
  def initialize
    @invoker = Invoker.new
    @light = Light.new
  end

  def party
    50.times do
      @invoker.record_and_execute(TurnOnCommand.new(@light))
      @invoker.record_and_execute(TurnOffCommand.new(@light))
    end
  end
end