设计模式笔记:命令模式

命令模式是一种行为设计模式,将命令的调用操作和具体执行解耦。

将一个请求封装成一个对象,用户使用不同的请求,使得能够对请求排队或记录日志,以及支持可撤销的操作。

命令基类定义命令执行Execute方法

1
2
3
4
class Command {
public:
virtual void Execute() = 0;
}

具体命令实现Execute方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// robotic arm
class RoboticArmCommand {
public:
void Execute() override
{
std::cout << "RoboticArm Command Execute." << std::endl;
}
}

// move
class MoveCommand {
public:
void Execute() override
{
std::cout << "Move Command Execute." << std::endl;
}
}

命令控制器类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class RobotInvoker {
public:
// 添加命令
void AddCommands(Command* command)
{
robotCommands_.push_back(command);
}

//执行系列命令
void ExecuteCommand() {
for (Command command : robotCommands_ {
command->Execute();
}
}

void clearCommand(){
robotCommands_.clear();
}

private:
std::list<Command*> robotCommands_;
}

将一个请求封装成一个对象,用户使用不同的请求,使得能够对请求排队或记录日志,以及支持可撤销的操作。

优点

  1. 将调用操作的对象与实现该操作的对象解耦。
  2. 方便扩展,增加新的命令容易,不需要改变已有类。
  3. 可以将多个命令配成复合指令。