假设我们选择了整个文件并删除了其内容。我们如何以节省空间的方式实现此方案的撤消操作。
您的问题有点模糊,但命令设计模式可能会对您有所帮助。通过这种方式,您可以封装命令的执行,但也可以选择调用 undo() 并将主题恢复到执行命令之前的状态。它通常用于应用程序中的撤消/重做操作堆栈。
例如,您可以有:
public interface Command{
public void exec();
public void undo();
}
然后,对于每个命令,您可以拥有:
public class DeleteContents implements Command{
SomeType previousState;
SomeType subject;
public DeleteContents(SomeType subject){
this.subject = subject; // store the subject of this command, eg. File?
}
public void exec(){
previousState = subject; // save the state before invoking command
// some functionality that alters the state of the subject
subject.deleteFileContents();
}
public void undo(){
subject.setFileContents(previousState.getFileContents()); // operation effectively undone
}
}
您可以将命令存储在数据结构(例如控制器)中,并且可以自由调用执行和撤消它们。这对你的情况有帮助吗?
这是一个链接:http://en.wikipedia.org/wiki/Command_pattern