0

假设我们选择了整个文件并删除了其内容。我们如何以节省空间的方式实现此场景的撤消操作。

4

1 回答 1

0

您的问题有点含糊,但命令设计模式可能会对您有所帮助。通过这种方式,您可以封装命令的执行,但也可以选择调用 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

于 2012-12-13T16:17:20.657 回答