Implementing Undo/Redo

Here is a code snippet for implementing the Undo/Redo.

Sample Code

</pre>
//interface defining the edit
 <strong> public interface IUndoableEdit</strong>
 {

//Perform the Undo operation
 bool Undo();

//Perform the Redo operation
 bool Redo();

//validates whether Undo operation can be performed on this edit   //in the current context
 bool CanUndo();

//validates whether Redo operation can be performed on this edit   //in the current context
 bool CanRedo();

void Dispose();

}

//Class providing the infrastructure for manging the IUndoableEdits
 <strong> public class UndoStack</strong>
 {
 //stack is used to store the edits..First In Last Out

private Stack undoStack;
 private Stack redoStack;

public UndoStack()
 {
 //initialize the stack
 redoStack = new Stack(100);
 undoStack = new Stack(100);
 }

public void AddEdit(IUndoableEdit  edit)
 {
 //validate input arguments
 undoStack.Push(edit);
 }

//Clear all the edits stored in the Stack.
 public void ClearAll()
 {
 undoStack.Clear();
 redoStack.Clear();
 }

public void Undo()
 {
 if(undoStack.Count == 0)
 {
 Console.Beep();
 return;
 }

IUndoableEdit edit = undoStack.Pop();

if(edit.CanUndo() && edit.Undo())
 {
 if(edit.CanRedo() )
 {
 redoStack.Push(edit)
 }
 }
 else
 {
 edit.Dispose();
 }

}

public void Redo()
 {
 if(redoStack.Count == 0)
 {
 Console.Beep();
 return;
 }

IUndoableEdit edit = redoStack.Pop();

if(edit.CanRedo() && edit.Redo())
 {
 if(edit.CanUndo() )
 {
 undoStack.Push(edit)
 }
 }
 else
 {
 edit.Dispose();
 }

}

}
<pre>
Advertisements

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: