命令模式(command):java
达到命令的发出者和执行者之间解耦,实现请求和执行分开。
示例:ide
命令模式测试类CommandTest.java测试
/** * 命令模式测试类 * * @author Kevin * @date 2016-3-16 */ public class CommandTest { public static void main(String[] args) { Receiver receiver = new Receiver(); Command command = new CommandImpl(receiver); Invoker invoker = new Invoker(command); invoker.action(); } }
命令接口类Command.javathis
/** * 命令接口 * * @author Kevin * @date 2016-3-16 */ public interface Command { /** * 执行 * * @author Kevin */ void execute(); }
命令实现类CommandImpl.javacode
/** * 命令实现类 * * @author Kevin * @date 2016-3-16 */ public class CommandImpl implements Command { /* 接收者 */ private Receiver receiver; public CommandImpl(Receiver receiver) { this.receiver = receiver; } @Override public void execute() { receiver.action(); } }
命令调用类Invoker.java接口
/** * 命令调用类 * * @author Kevin * @date 2016-3-16 */ public class Invoker { /* 命令接口 */ private Command command; public Invoker(Command command) { this.command = command; } /** * 行动 * * @author Kevin */ public void action() { command.execute(); } }
命令接收类Receiver.javaio
/** * 命令接收类 * * @author Kevin * @date 2016-3-16 */ public class Receiver { /** * 行动 * * @author Kevin */ public void action() { System.out.println("command received!"); } }