一、什么是命令模式
将请求封装成命令对象,请求的具体执行由命令接收者执行;
二、补充说明
命令发送者与命令执行者解耦;
可扩展命令模式:对请求排队或者记录请求日志,以及支持可撤销的操作;
每一个命令都是一个操作:请求的一方发出请求,要求执行一个操作;接收的一方收到请求,并执行操作。
三、角色
抽象命令
具体命令
命令接收者:执行命令
命令调用者
客户端:发送
四、例子,JAVA实现
一个开关灯例子,客户端发送开关灯命令,命令调用者负责调用调用执行命令;
抽象命令:
package com.pichen.dp.behavioralpattern.command;
public interface Command {
public void execute();
}
具体命令:开灯和关灯命令
package com.pichen.dp.behavioralpattern.command;
public class LightOffCommand implements Command{
private Receiver receiver;
/**
*
*/
public LightOffCommand(Receiver receiver) {
this.receiver = receiver;
}
/**
* @see com.pichen.dp.behavioralpattern.command.Command#execute()
*/
@Override
public void execute() {
this.receiver.turnOFF();
}
}
package com.pichen.dp.behavioralpattern.command;
public class LightOnCommand implements Command{
private Receiver receiver;
/**
*
*/
public LightOnCommand(Receiver receiver) {
this.receiver = receiver;
}
/**
* @see com.pichen.dp.behavioralpattern.command.Command#execute()
*/
@Override
public void execute() {
receiver.turnON();
}
}
命令接受者:负责执行具体命令操作
package com.pichen.dp.behavioralpattern.command;
public class Receiver {
public void turnON() {
System.out.println("执行开灯操作~");
}
public void turnOFF() {
System.out.println("执行关灯操作~");
}
}
命令调用者:负责调用
package com.pichen.dp.behavioralpattern.command;
public class Invoker {
public void execute(Command command){
command.execute();
}
}
客户端:开关灯例子
package com.pichen.dp.behavioralpattern.command;
public class Main {
public static void main(String[] args) {
Receiver receiver = new Receiver();
Invoker invoker = new Invoker();
Command turnOnLight = new LightOnCommand(receiver);
Command turnOffLight = new LightOffCommand(receiver);
invoker.execute(turnOnLight);
invoker.execute(turnOffLight);
}
}
执行结果