Skip to content

Instantly share code, notes, and snippets.

@uxdxdev
Last active January 27, 2023 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uxdxdev/7426ccd8680628ad8802f1eacbd82a29 to your computer and use it in GitHub Desktop.
Save uxdxdev/7426ccd8680628ad8802f1eacbd82a29 to your computer and use it in GitHub Desktop.
# Command interface
module ICommand
def execute
raise NotImplementedError
end
end
# Concrete commands
class SubmitCommand
include ICommand
def initialize(receiver)
@receiver = receiver
end
def execute
@receiver.submit
end
end
class DeleteCommand
include ICommand
def initialize(receiver)
@receiver = receiver
end
def execute
@receiver.delete
end
end
# Invoker
class Button
def initialize(command)
@command = command
end
def click
@command.execute
end
def switch_command(command)
@command = command
end
end
# Receiver
class Form
def submit
puts "form submitted"
end
def delete
puts "form deleted"
end
end
# Client
class Application
def start
form = Form.new
submit_command = SubmitCommand.new(form)
button = Button.new(submit_command)
button.click
delete_command = DeleteCommand.new(form)
button.switch_command(delete_command)
button.click
end
end
app = Application.new
app.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment