Command
Definition
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
UML class diagram
Participants
- Command
- declares an interface for executing an operation
- ConcreteCommand
- defines a binding between a Receiver object and an action
- implements Execute by invoking the corresponding operation(s) on Receiver
- Client
- creates a ConcreteCommand object and sets its receiver
- Invoker
- asks the command to carry out the request
- Receiver
- knows how to perform the operations associated with carrying out the request.
Sample code in Java
package com.hong.command; abstract class Command { protected Receiver receiver; public Command(Receiver receiver) { this.receiver = receiver; } public abstract void execute(); } class ConcreteCommand extends Command { public ConcreteCommand(Receiver recever) { super(recever); } @Override public void execute() { System.out.println("execute command from ConcreteCommand object."); if(receiver != null) receiver.action(); } } class Receiver { public void action() { System.out.println("Action from receiver class"); } } class Invoker { private Command command; public void setCommand(Command command) { this.command = command; } public void executeCommand() { System.out.println("execute command from Invoker"); command.execute(); } } public class Command_structure { public static void main(String[] args) { Command command1 = new ConcreteCommand(new Receiver()); Command command2 = new ConcreteCommand(new Receiver()); Invoker invoker = new Invoker(); //Invoke command1. invoker.setCommand(command1); invoker.executeCommand(); //Invoke command2. invoker.setCommand(command2); invoker.executeCommand(); } }