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>
No comments yet
Leave a reply