Step 1: Establish a requester (commander) interface to encapsulate command execution
public interface Command { public void exe(); }
Step 2: Create an interface implementation class, save the receiver instance, and rewrite the execution method of the command interface
public class MyCommand implements Command { private Receiver receiver; public MyCommand(Receiver receiver) { this.receiver=receiver; } @Override public void exe() { receiver.action(); } }Step 3: Command the receiver Receiver
public class Receiver { public void action() { System.out.println("Command received"); } }
Step 4: Create the invoker Invoker
public class Invoker { private Command command; public Invoker(Command command) { this.command=command; } public void action() { command.exe(); } }
Step 5: Test
public class Test { public static void main(String[] args) { Receiver receiver=new Receiver(); Command command=new MyCommand(receiver); Invoker invoker=new Invoker(command); invoker.action(); } }