DEV Community

eidher
eidher

Posted on • Edited on

Command Pattern

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

Alt Text

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.

Code

public class Main { public static void main(String[] args) { Receiver receiver = new Receiver(); Command command = new ConcreteCommand(receiver); Invoker invoker = new Invoker(); invoker.setCommand(command); invoker.executeCommand(); } } public abstract class Command { protected Receiver receiver; public Command(Receiver receiver) { this.receiver = receiver; } public abstract void execute(); } public class ConcreteCommand extends Command { public ConcreteCommand(Receiver receiver) { super(receiver); } @Override public void execute() { receiver.action(); } } public class Receiver { public void action() { System.out.println("Called Receiver.action()"); } } public class Invoker { private Command command; public void setCommand(Command command) { this.command = command; } public void executeCommand() { command.execute(); } } 
Enter fullscreen mode Exit fullscreen mode

Output

Called Receiver.action() 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)