命令模式应用场景
在软件开发系统中,“方法的请求者”与“方法的实现”之间经常存在着紧密的耦合关系,这不利于软件功能的扩展与维护。例如,想对方法进行“撤销,重做,记录”等处理很不方便,因此,“如何将方法的请求着与实现着解耦?”变得很重要,命令模式就能很好的解决这个问题。
在我们看电视的时候,只需要按一下遥控器就能完成切换频道,这就是命令模式。将换台的请求和换台的处理完全的解耦。电视遥控器(命令发送者)通过按钮(具体命令)来遥控电视机(命令接受者);
命令模式代码示例
命令接口
package com.demo.test.command.iml;
public interface Command {
public void execute();
}
接受者接口
package com.demo.test.command.iml;
public interface Receiver {
public void action();
}
调用者接口
package com.demo.test.command;
import com.demo.test.command.iml.Command;
import java.util.ArrayList;
import java.util.List;
public class Invoker {
private List<Command> commands = new ArrayList<>();
public Invoker(Command command){
this.commands.add(command);
}
public void setCommand(Command command) {
this.commands.add(command);
}
public void call(){
for(Command command:commands){
command.execute();
}
}
}
具体命令接口A
package com.demo.test.command;
import com.demo.test.command.iml.Command;
import com.demo.test.command.iml.Receiver;
public class ConcreteCommandA implements Command {
private ReceiverA receiver;
public ConcreteCommandA(){
this.receiver = new ReceiverA();
}
@Override
public void execute() {
receiver.action();
}
}
具体接口命令B
package com.demo.test.command;
import com.demo.test.command.iml.Command;
import com.demo.test.command.iml.Receiver;
public class ConcreteCommandB implements Command {
private ReceiverB receiver;
public ConcreteCommandB( ){
this.receiver = new ReceiverB();
}
@Override
public void execute() {
receiver.action();
}
}
具体接收人A
package com.demo.test.command;
import com.demo.test.command.iml.Receiver;
public class ReceiverA implements Receiver {
@Override
public void action() {
System.out.println("接收者A,执行任务。");
}
}
具体接收人B
package com.demo.test.command;
import com.demo.test.command.iml.Receiver;
public class ReceiverB implements Receiver {
@Override
public void action() {
System.out.println("接收者b,执行任务");
}
}
客户端
package com.demo.test.command;
import com.demo.test.command.iml.Command;
public class Client {
public static void main(String[] agr){
Command commandA = new ConcreteCommandA();
Command commandB = new ConcreteCommandB();
Invoker invoker = new Invoker(commandA);
invoker.setCommand(commandB);
invoker.call();
}
}