将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可取消的操作。
命令模式,把请求封装成一个命令,然后去执行该命令。命令模式设计的目的就是把调用方发送命令和执行方执行命令分开。
在这里我们根据案例来具体学习命令模式。以下是代码示例及知识点详解。
我们首先创建作为命令的接口 Command
,然后创建作为作为请求的 Light
类。实体命令类FlipUpCommand
和FlipDownCommand
,实现了接口Command
,将执行实际的命令处理。创建作为调用对象的Switch
类,它能接收并执行命令。
定义一个命令接口。
public interface Command {
void execute();
}
创建请求类。
public class Light {
public Light() {
}
public void turnOn() {
System.out.println("The light is on");
}
public void turnOff() {
System.out.println("The light is off");
}
}
创建实现了Command
的第一个实体类。
public class FlipUpCommand implements Command {
private Light theLight;
public FlipUpCommand(Light light) {
this.theLight = light;
}
public void execute(){
theLight.turnOn();
}
}
创建实现了Command
的第二个实体类。
public class FlipDownCommand implements Command {
private Light theLight;
public FlipDownCommand(Light light) {
this.theLight = light;
}
public void execute() {
theLight.turnOff();
}
}
创建命令调用类。
public class Switch {
private List<Command> history = new ArrayList<Command>();
public Switch() {
}
public void storeAndExecute(Command cmd) {
this.history.add(cmd); // optional
cmd.execute();
}
}
执行代码,测试命令模式。
public class PressSwitch {
public static void main(String[] args){
Light lamp = new Light();
Command switchUp = new FlipUpCommand(lamp);
Command switchDown = new FlipDownCommand(lamp);
Switch mySwitch = new Switch();
try {
if ("ON".equalsIgnoreCase(args[0])) {
mySwitch.storeAndExecute(switchUp);
}
else if ("OFF".equalsIgnoreCase(args[0])) {
mySwitch.storeAndExecute(switchDown);
}
else {
System.out.println("Argument \"ON\" or \"OFF\" is required.");
}
} catch (Exception e) {
System.out.println("Arguments required.");
}
}
}
总结
命令模式的设计思想是把命令的创建和执行分离,使得调用者无需关心具体的执行过程。
通过封装Command
对象,命令模式可以保存已执行的命令,从而支持撤销、重做等操作。