大三每日总结
软件设计 石家庄铁道大学信息学院
实验16:命令模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解命令模式的动机,掌握该模式的结构;
2、能够利用命令模式解决实际问题。
[实验任务一]:多次撤销和重复的命令模式
某系统需要提供一个命令集合(注:可以使用链表,栈等集合对象实现),用于存储一系列命令对象,并通过该命令集合实现多次undo()和redo()操作,可以使用加法运算来模拟实现。
实验要求:
1.提交类图;
2.提交源代码;
package command;
public abstract class AbstractCommand {
public abstract int execute(int value);
public abstract int undo();
public abstract int redo();
}
package command;
import java.util.Stack;
public class AddCommand extends AbstractCommand {
private Adder adder = new Adder();
private Stack<Integer> unStack = new Stack<Integer>();
private Stack<Integer> reStack = new Stack<Integer>();
public int undo() {
int i=0;
if (unStack.isEmpty()) {
i=-1;
}else{
Integer pop = unStack.pop();
reStack.push(pop);
if(!unStack.isEmpty()){
i=unStack.peek();
}
}
return i;
}
public int redo() {
int i=0;
if (reStack.isEmpty()) {
i=-1;
}else{
Integer pop = reStack.pop();
unStack.push(pop);
i=pop;
}
return i;
}
public int execute(int value) {
int v = 0;
if (unStack.isEmpty()) {
v = adder.add(value);
unStack.push(v);
} else {
v = adder.add(value);
unStack.push(v);
if (!reStack.isEmpty()) {
for (int i = 0; i < reStack.size(); i++) {
reStack.pop();
}
}
}
return v;
}
}
package command;
public class Adder {
private int num =0;
public int add(int value) {
num+=value;
return num;
}
}
package command;
public class CalculatorForm {
private AbstractCommand command;
public void setCommand(AbstractCommand command) {
this.command =command;
}
public void compute(int value) {
command.execute(value);
}
public void undo() {
int i = command.undo();
if(i==-1){
System.out.println("缓存中已不存在数据");
}else{
System.out.println("执行成功,运算结果是:"+i);
}
}
public void redo() {
int i = command.redo();
if(i==-1){
System.out.println("已恢复至最新数据");
}
else{
System.out.println("执行成功,运算结果是:"+i);
}
}
}
package command;
public class Client {
public static void main(String[] args) {
CalculatorForm form = new CalculatorForm();
AddCommand command = new AddCommand();
form.setCommand(command);
System.out.println("计算过程");
form.compute(1);
form.compute(2);
form.compute(3);
form.compute(4);
System.out.println("撤回过程");
form.undo();
form.undo();
form.undo();
form.undo();
form.undo();
System.out.println("恢复过程");
form.redo();
form.redo();
form.redo();
form.redo();
form.redo();
}
}
3. 注意编程规范。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南