命令模式将"行为请求者与行为实现者进行解耦"
在请求和实现之间加一中间层
如实现四则运算例子
//运算接口ICommand.java
package demo;
public interface ICommand {
public void handle(int num1,int num2);
}
//实现运算Mul.java
package demo;
public class Mul implements ICommand {
public void handle(int num1,int num2) {
System.out.print(num1*num2);
System.out.println();
}
}
//Plus.java
package demo;
public class Plus implements ICommand {
public void handle(int num1,int num2) {
System.out.print(num1+num2);
System.out.println();
}
}
//Mul.java
package demo;
public class Mul implements ICommand {
public void handle(int num1,int num2) {
System.out.print(num1*num2);
System.out.println();
}
}
//Sub.java
package demo;
public class Sub implements ICommand {
public void handle(int num1,int num2) {
System.out.print(num1-num2);
System.out.println();
}
}
//中间层,命令层
package demo;
import java.util.HashMap;
import java.util.Map;
public class Commands {
// 命令模式的中间层,完成接收命令,统一执行
private Map map;
public Commands() {
map = new HashMap();
addCommand("1", new Plus());
addCommand("2", new Sub());
addCommand("3", new Mul());
}
public void addCommand(String cmdId, ICommand cmd) { 用来收集命令
map.put(cmdId, cmd);
}
public void doRequest(String cmdId,int num1,int num2) {
//统一执行的方法
ICommand cmd = (ICommand)map.get(cmdId);
cmd.handle(num1,num2);
}
}
//调用TestMain.java
package demo;
public class testMain {
public static void main(String[] args) {
Commands cmds = new Commands();
cmds.doRequest("1", 100,5);
cmds.doRequest("2", 100,5);
cmds.doRequest("3", 100,5);
}
}