每日博客

命令模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解命令模式的动机,掌握该模式的结构;

2、能够利用命令模式解决实际问题。

 

 

[实验任务一]:多次撤销和重复的命令模式

某系统需要提供一个命令集合(注:可以使用链表,栈等集合对象实现),用于存储一系列命令对象,并通过该命令集合实现多次undo()和redo()操作,可以使用加法运算来模拟实现。

C++

#include<iostream>
using namespace std;

class AbstractCommand{
public:
virtual int execute(int value) = 0;
virtual int undo() = 0;
virtual int redo() = 0;
};

class Adder {
private:
int number = 0;
public:
int add(int value) {
number = number + value;
return number;
}
};

class ConcreteCommand :public AbstractCommand{
private:
Adder* adder = new Adder();
int _value=0;
public:
int execute(int value) {
_value = value;
return adder->add(_value);
}
int undo() {
return adder->add(-_value);
}
int redo() {
return adder->add(_value);
}
};

class CalculatorForm{
private:
AbstractCommand* _command;
public:
void setAbstractCommand(AbstractCommand* command) {
_command = command;
}
void computer(int value) {
int i = _command->execute(value);
cout << "执行运算,运算结果为:" << i << endl;
}
void undo() {
int i = _command->undo();
cout << "执行undo,运算结果为:" << i << endl;
}
void redo() {
int i = _command->redo();
cout << "执行redo,运算结果为:" << i << endl;
}
};

int main() {
CalculatorForm* form = new CalculatorForm();
AbstractCommand* command = new ConcreteCommand();
form->setAbstractCommand(command);
form->computer(10);
form->computer(20);
form->undo();
form->redo();
form->computer(30);
form->undo();
form->redo();
}

posted @ 2021-10-30 20:18  谦寻  阅读(42)  评论(0编辑  收藏  举报