0

Say we have selected the entire file and deleted its content. How can we implement the undo operation for this scenario in a space efficient way.

user1846721
  • 61
  • 1
  • 1
  • 4

1 Answers1

0

Your question is a bit vague, but the Command design pattern might help you. In this way you can encapsulate the execution of a command, but also have the option to call undo() and revert the subject to the state prior to the command being executed. It's often used for the Undo/Redo stack of operations in applications.

As an example you could have:

public interface Command{

  public void exec();
  public void undo();
}

Then for each command you could have:

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
  }

}

You can store your Commands in a data structure (eg. a controller) and can freely invoke execute and undo on them. Does that help with your situation?

Here's a link: http://en.wikipedia.org/wiki/Command_pattern

Darius
  • 5,180
  • 5
  • 47
  • 62
  • For implementing a simple undo operation we can use stack, but what if we want do undo operation in the case where we did CTRL+A and then delete.Can we still use the stack? – user1846721 Dec 14 '12 at 06:07