命令模式

案例

1
2
3
4
5
1.我们买了一套智能家电,有照明灯、风扇、冰箱、洗衣机,我们只要在手机上安装app就可以控制对这些家电工作。
2.这些智能家电来自不同的厂家,我们不想针对每一种家电都安装一个App,分别控制,我们希望只要一个app就可以控制全部智能家电。
3.要实现一个app控制所有智能家电的需要,则每个智能家电厂家都要提供一个统一的接口给app调用,这时就可以考虑使用命令模式。
4.命令模式可将“动作的请求者”从“动作的执行者”对象中解耦出来.
5.在我们的例子中,动作的请求者是手机app,动作的执行者是每个厂商的一个家电产品

基本介绍

命令模式( command Pattern):在软件设计中,我们经常需要向某些对象发送请求,但是并不知道请求的接收者是谁,也不知道被请求的操作是哪个.
我们只需在程序运行时指定具体的请求接收者即可,此时,可以使用命令模式来进行设计

命名模式使得请求发送者与请求接收者消除彼此之间的耦合,让对象之间的调用关系更加灵活,实现解耦。

在命名模式中,会将一个请求封装为一个对象,以便使用不同参数来表示不向的请求(即命名),同时命令模式也支持可撤销的操作。

通俗易懂的理解:将军发布命令,士兵去执行。其中有几个角色:将军(命令发布者)、王兵(命令的具体执行者)、命令(连接将军和士兵)。

image-20220110171326231
  • Invoker是调用者,
  • Receiver是接收者,知道如何执行一个请求相关的操作
  • Command是命令,实现了Command接口,持有接收对象
  • ConcreteCommand:将一个接受者对象与一个动作,调用接受者响应的操作,实现execute。

解决问题

开关问题

接口

1
2
3
4
5
6
7
public interface Command {

//执行动作
public void execute();
//撤销
public void undo();
}

实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class LightOffCommand implements Command {

//聚合LightReceiver
LightReceiver light;

public LightOffCommand(LightReceiver light) {
this.light = light;
}

public void execute() {
//调用接受者的方法
light.off();
}

public void undo() {
light.on();
}
}

public class LightOnCommand implements Command {

//聚合LightReceiver
LightReceiver light;

public LightOnCommand(LightReceiver light) {
this.light = light;
}

public void execute() {
//调用接受者的方法
light.on();
}

public void undo() {
light.off();
}
}

//没有命令空执行。用于初始化每个按钮,当调用空命令时,对象什么都不做
//这也是一种设计模式,可以省掉对空的判断。
public class NoCommand implements Command{
public void execute() {

}

public void undo() {

}
}

接收者

1
2
3
4
5
6
7
8
9
public class LightReceiver {
public void on(){
System.out.println("电灯打开了");
}

public void off(){
System.out.println("电灯关闭了");
}
}

调用者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class RemoteController {

//开按钮的命令数组
Command[] onCommands;
Command[] offCommands;

//执行撤销命令
Command undoCommand;

//构造器完成对按钮的初始化
public RemoteController(){
this.onCommands = new Command[5];
this.offCommands = new Command[5];

for(int i = 0; i < 5; i++){
onCommands[i] = new NoCommand();
offCommands[i] = new NoCommand();
}
}

//给我们的按钮设置你需要的按钮设置命令
public void setCommand(int no, Command onCommand, Command offCommand){
onCommands[no] = onCommand;
offCommands[no] = offCommand;
}

//按下开的按钮
public void onButtonWasPushed(int no){
//找到你按下的开按钮,并调用对应的方法
onCommands[no].execute();
//记录这次操作,用于撤销
undoCommand = onCommands[no];
}

//按下关的按钮
public void offButtonWasPushed(int no){
//找到你按下的开按钮,并调用对应的方法
offCommands[no].execute();
//记录这次操作,用于撤销
undoCommand = offCommands[no];
}

//按下撤销按钮
public void undoButtonWasPushed(){
undoCommand.undo();
}

}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Client {
public static void main(String[] args) {
//使用命令模式,完成遥控器对电灯的操作
//创建电灯对象
LightReceiver lightReceiver = new LightReceiver();

//创建电灯相关开关
LightOnCommand lightOnCommand = new LightOnCommand(lightReceiver);
LightOffCommand lightOffCommand = new LightOffCommand(lightReceiver);

//需要一个遥控器
RemoteController remoteController = new RemoteController();

//设置相关命令
remoteController.setCommand(0, lightOnCommand, lightOffCommand);

remoteController.offButtonWasPushed(0);
remoteController.onButtonWasPushed(0);
}
}

源码使用

JdbcTemplete

JdbcTemplate是invoke,execute方法调用了action.doInSatement,不同的实现对线,对应不同的实现逻辑。

匿名内部类实现命令接口,同时充当了命令接受者。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
@Override
public <T> T query(final String sql, final ResultSetExtractor<T> rse) throws DataAccessException {
Assert.notNull(sql, "SQL must not be null");
Assert.notNull(rse, "ResultSetExtractor must not be null");
if (logger.isDebugEnabled()) {
logger.debug("Executing SQL query [" + sql + "]");
}

class QueryStatementCallback implements StatementCallback<T>, SqlProvider {
@Override
public T doInStatement(Statement stmt) throws SQLException {
ResultSet rs = null;
try {
rs = stmt.executeQuery(sql);
ResultSet rsToUse = rs;
if (nativeJdbcExtractor != null) {
rsToUse = nativeJdbcExtractor.getNativeResultSet(rs);
}
return rse.extractData(rsToUse);
}
finally {
JdbcUtils.closeResultSet(rs);
}
}
@Override
public String getSql() {
return sql;
}
}

return execute(new QueryStatementCallback());
}

//
@Override
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");

Connection con = DataSourceUtils.getConnection(getDataSource());
Statement stmt = null;
try {
Connection conToUse = con;
if (this.nativeJdbcExtractor != null &&
this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativeStatements()) {
conToUse = this.nativeJdbcExtractor.getNativeConnection(con);
}
stmt = conToUse.createStatement();
applyStatementSettings(stmt);
Statement stmtToUse = stmt;
if (this.nativeJdbcExtractor != null) {
stmtToUse = this.nativeJdbcExtractor.getNativeStatement(stmt);
}
//调用
T result = action.doInStatement(stmtToUse);
handleWarnings(stmt);
return result;
}
catch (SQLException ex) {
// Release Connection early, to avoid potential connection pool deadlock
// in the case when the exception translator hasn't been initialized yet.
JdbcUtils.closeStatement(stmt);
stmt = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex);
}
finally {
JdbcUtils.closeStatement(stmt);
DataSourceUtils.releaseConnection(con, getDataSource());
}
}
}

StatementCallback,命令接口

1
2
3
4
5
public interface StatementCallback<T> {

T doInStatement(Statement stmt) throws SQLException, DataAccessException;

}

注意事项

  • 发起请求的对象与执行请求的对象解耦。发起请求的对象是调用者,调用者只要调用命令对象的execute()方法就可以让接收者工作,而不必知道具体的接收者对象是谁、是如何实现的,命令对象会负责让接收者执行请求的动作,也就是说:”请求发起者”和“请求执行者”之间的解耦是通过命令对象实现的,命令对象起到了纽带桥梁的作用
  • 容易设计一个命令队列。只要把命令对象放到列队,就可以多线程的执行命令
  • 容易实现对请求的撤销和重做
  • 命令模式不足:可能导致某些系统有过多的具体命令类,增加了系统的复杂度,这点在在使用的时候要注意
  • 空命令也是一种设计模式,它为我们省去了判空的操作。在上面的实例中,如果没有用空命令,我们每按下一个按键都要判空,这给我们编码带来一定的麻烦。
  • 命令模式经典的应用场景:界面的一个按钮都是一条命令、模拟CMD (DOS命令)订单的撤销/恢复、触发-反馈机制