Command pattern encapsulates a request under an object as command, and passed to invoker object. It allows the parameterization of clients with different requests, queue or log requests. Normally, command pattern can be applied when we need to issue requests to objects without knowing anything about the operation being requested or the receiver of the request.
Command patter decouples Invoker (invokes operation) from Receiver (know how to perform the operation). The following diagram demonstrates how it works.
In the diagram, an Invoker treats a Command object as a black box. If it executes operation() method, it will call the command object execute() method that will call the receiver’s one action method.
Step 1 implement a receiver class
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package net.tecbar.designpattern.command; public class Receiver { public void action1() { System.out.println("Receiver execute action 1"); } public void action2() { System.out.println("Receiver execute action 2"); } } |
Step 2 define Command interface
1 2 3 4 5 6 7 |
package net.tecbar.designpattern.command; public interface Command { void execute(); } |
Step 3 Create concrete command class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package net.tecbar.designpattern.command; public class ConcreteCommand1 implements Command { private Receiver receiver; public ConcreteCommand1(Receiver receiver) { this.receiver = receiver; } @Override public void execute() { receiver.action1(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package net.tecbar.designpattern.command; public class ConcreteCommand2 implements Command { private Receiver receiver; public ConcreteCommand2(Receiver receiver) { this.receiver = receiver; } @Override public void execute() { receiver.action2(); } } |
Step 4 create a Invoker class
1 2 3 4 5 6 7 8 9 |
package net.tecbar.designpattern.command; public class Invoker { public void operation(Command command) { command.execute(); } } |
Step 5 write a demo client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package net.tecbar.designpattern.command; public class Client { public static void main(String[] args) { Receiver receiver = new Receiver(); Command cmd1 = new ConcreteCommand1(receiver); Command cmd2 = new ConcreteCommand2(receiver); Invoker invoker = new Invoker(); invoker.operation(cmd1); System.out.println("======================="); invoker.operation(cmd2); } } |
Output
1 2 3 4 5 |
Receiver execute action 1 ======================= Receiver execute action 2 |
Pingback: Software Design Patterns