命令模式的目的就是将命令的发出者和执行者之间解耦。
我们以司令员给士兵发布指令执行为例:
//命令接口类
public interface Command
{
void action();
}
public class MyCommand implements Command
{
private Receiver receiver;
public MyCommand(Receiver receiver)
{
this.receiver = receiver;
}
@override
public void exe()
{
receiver.action();
}
}
//士兵
public class Receiver
{
public void action()
{
System.out.println("command received");
}
}
//司令官
public class Invoker
{
private Command command;
public Invoker(Command command)
{
this.command = command;
}
public void action()
{
command.exe();
}
}
//测试类
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();
}
}