Skip to content

Instantly share code, notes, and snippets.

@vmoravec
Created January 5, 2013 20:01
Show Gist options
  • Save vmoravec/4463359 to your computer and use it in GitHub Desktop.
Save vmoravec/4463359 to your computer and use it in GitHub Desktop.
Command pattern
class Command
def initialize(description, proc1, proc2)
@description = description
@function = proc1
@inverse = proc2
end
def execute
@function.call unless @function.nil?
end
def unexecute
@inverse.call unless @inverse.nil?
end
end
class CreateFile < Command
def initialize
proc1 = Proc.new do
puts "File Created"
end
proc2 = Proc.new do
puts "File Destroyed"
end
super("creating new file", proc1, proc2)
end
end
class CheckMemory < Command ##ireversible
def initialize
proc1 = Proc.new do
puts "Checking Memory..."
end
proc2 = Proc.new do
puts "Mem Check need not be reversed"
end
super("Checking memory avalability", proc1, proc2)
end
end
class Installer
def initialize
@commands = []
end
def add_command command
@commands << command
end
def install
@commands.each {|c| c.execute}
end
def uninstall
@commands.reverse.each do |command|
command.unexecute
end
end
end
installer = Installer.new
installer.add_command(CheckMemory.new)
installer.add_command(CreateFile.new)
installer.installinstaller.uninstall
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment