java如何撤回
Java中实现撤销操作的方法
在Java中实现撤销功能通常依赖于设计模式或数据结构来记录操作历史。以下是几种常见方法:
命令模式(Command Pattern)
命令模式是处理撤销操作的经典设计模式。将每个操作封装为对象,存储执行和撤销的逻辑:

interface Command {
void execute();
void undo();
}
class ConcreteCommand implements Command {
private Receiver receiver;
private String previousState;
public void execute() {
previousState = receiver.getState();
receiver.action();
}
public void undo() {
receiver.setState(previousState);
}
}
备忘录模式(Memento Pattern)
通过保存对象状态快照实现撤销:

class Originator {
private String state;
public Memento saveToMemento() {
return new Memento(state);
}
public void restoreFromMemento(Memento m) {
state = m.getSavedState();
}
}
class Memento {
private final String state;
public Memento(String stateToSave) {
state = stateToSave;
}
}
使用栈结构存储操作历史
利用栈的LIFO特性实现多级撤销:
Stack<Command> commandHistory = new Stack<>();
// 执行命令时
command.execute();
commandHistory.push(command);
// 撤销时
if (!commandHistory.isEmpty()) {
Command lastCommand = commandHistory.pop();
lastCommand.undo();
}
文本编辑器的撤销实现示例
对于文本处理场景,可以保存文本变化历史:
class TextEditor {
private StringBuilder text;
private Stack<String> history = new Stack<>();
public void append(String str) {
history.push(text.toString());
text.append(str);
}
public void undo() {
if (!history.isEmpty()) {
text = new StringBuilder(history.pop());
}
}
}
注意事项
- 深拷贝与浅拷贝:状态保存时需注意对象拷贝深度
- 内存管理:历史记录可能占用大量内存,需设置合理上限
- 线程安全:多线程环境下需保证操作原子性
选择哪种方法取决于具体应用场景和性能要求。命令模式适合离散操作,备忘录模式适合需要保存完整对象状态的场景。






