命令模式(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!"); } }