所谓命令模式本质上讲就是对请求的封装:
那我们在什么时候使用呢?
1 如果需要执行的动作需要被抽取出来
2 需要在不同的时刻指定请求
其实命令式最主要的作用还是用于类之间的解耦。
结构图:
示例代码:
package Proxy.command;
public class Invoker {
//调用哪一个命令
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public Command getCommand() {
return command;
}
//执行命令
public void execute (){
getCommand().action();
}
}
package Proxy.command;
public interface Command {
void action();
}
package Proxy.command;
public class ConcreateCommand1 implements Command {
private Receiver receiver;
public ConcreateCommand1(Receiver receiver) {
super();
this.receiver = receiver;
}
@Override
public void action() {
this.receiver.execute();
}
}
package Proxy.command;
public class ConcreateCommand2 implements Command {
private Receiver receiver;
public ConcreateCommand2(Receiver receiver) {
super();
this.receiver = receiver;
}
@Override
public void action() {
this.receiver.execute();
}
}
package Proxy.command;
public class Invoker {
//调用哪一个命令
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public Command getCommand() {
return command;
}
//执行命令
public void execute (){
getCommand().action();
}
}
package Proxy.command;
public class ReceiverA implements Receiver {
@Override
public void execute() {
System.out.println("我是A接收者");
}
}
package Proxy.command;
public class ReceiverB implements Receiver {
@Override
public void execute() {
System.out.println("我是B接收者");
}
}
package Proxy.command;
public class ReceiverC implements Receiver {
@Override
public void execute() {
System.out.println("我是C接收者");
}
}
package Proxy.command;
public class Client {
public static void main(String[] args) {
//先声明调用者
Invoker invoker = new Invoker();
//定义接受者
Receiver receiver = new ReceiverB();
//定义一个具体的命令
Command command = new ConcreateCommand1(receiver);
invoker.setCommand(command);
invoker.execute();
}
}
现在有这样的一个应用场景:
我现在需要定义一个方法,这个方法内部大部分功能或者步骤已经确定,但是有小部分不能确定,也就是所谓的动态代码。
举个列子,我现在在方法内部处理一个数组对象,但是数组对象的处理方式并不是确定的,需要根据调用的时候才能确定。
但是Java又不支持直接传入一个java 代码块给方法,怎么办呢?
所以我们有必要对这部分代码进行封装,但是封装的方法也不允许独立存在,在Java 世界,类才是一等的。所以我们实际
传到该方法的是一个对象。该对象通常是一个接口的匿名子类。该接口通常称为命令接口,这种设计模式也称为命令模式。
public class ProcessArray {
//Command用于处理数组的逻辑
public void iterateArray(int[] target,Command command){
command.process(target);
}
}
//Command 接口
public interface Command {
public abstract void process(int[] target);
}
具体完整的示例代码:
public class ProcessArrayTest {
public static void main(String[] args) {
ProcessArray processArray = new ProcessArray();
int [] target = {1,3,5,7,9,11};
//第一次处理数组
processArray.iterateArray(target, new Command() {
public void process(int[] target) {
for(int tmp : target){
System.out.println("current element:"+tmp);
}
}
});
//第二次处理数组
processArray.iterateArray(target, new Command() {
public void process(int[] target) {
int sum = 0;
for(int tmp : target){
sum += tmp;
}
System.out.println("Total :"+sum);
}
});
}
}