命令模式:将请求封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。支持撤销
可以分成四部分:命令接口及命令对象Command、客户Client、调用者Invoker、接收者Receiver
实现命令接口
public interface Command{
public void execute(); //用来绑定接收者和一组动作
}
建立命令对象,实现电灯接收者的打开命令
public class LightOnCommand implements Command{
Light light;
public LightOnCommand(Light light){
this.light=light;
}
public void execute(){
light.on();
}
}
调用者内传入命令对象
public class SimpleRemoteControl{
Command slot;
public SimpleRemoteControl(){}
public void satCommand(Command command){
slot=command;
}
public void buttonWasPressed(){
slot.execute();
}
}
客户
public class RemoteControlTest{
public Ststic void main(String[] args){
SimpleRemoteControl remote =new SimpleRemoteControl(); //传入调用者
Light light=new Light(); //传入接收者
LightCommand lightOn=new LightOnCommand(light); //命令对象绑定接收者对象
remote.setCommand(lightOn); //调用者绑定命令对象
remote.buttonWasPresses(); //调用者通过命令对象调用接收者对象的方法
}
}
命令模式封装了接收者的一系列动作,实现了在调用者和接收者之间解耦。
撤销功能
在Command中加入一个undo方法,若只有两种状态那么undo执行除execute之外的那种
若有多种状态,就需要一个变量在execute方法执行时记录状态,根据这个状态在uodo中实现方法
宏命令
//用一个命令数组储存要执行的命令对象
public class MacroCommand implements Command{
Command[] commands;
public MacroCommand(Command[] commands){
this.commands=commands;
}
public void execute(){
for(int i=0;i<commands.length;i++)
commands[i].execute();
}
}
//客户类中,生成多个命令对象放到命令对象数组中,再作为参数生成MacroCommand对象
//命令对象中与硬编码调用相比使用数组要更加灵活
日程安排,线程池,工作队列,日志请求。。。