一 使用Command模式如下:
二使用Singleton的UndoManager如下:
三C#的类代码如下:
public interface ICommand
{
void Execute();
void Reverse();
}
public class ACommand : ICommand
{
void Execute(){};
void Reverse(){};
}
public class BCommand : ICommand
{
void Execute(){};
void Reverse(){};
}
public class CCommand : ICommand
{
void Execute(){};
void Reverse(){};
}
public class UndoManager
{
public UndoManager()
{
UndoStack = new Stack < ICommand > ();
RedoStack = new Stack < ICommand > ();
}
public Stack < ICommand > UndoStack { get ; protected set ; }
public Stack < ICommand > RedoStack { get ; protected set ; }
public bool CanUndo { get { return UndoCommands.Count > 0 ; } }
public bool CanRedo { get { return RedoCommands.Count > 0 ; } }
public void Execute(ICommand command)
{
if (command == null ) return ;
// Execute command
command.Execute();
UndoStack.Push(command);
// Clear the redo history upon adding new undo entry.
// This is a typical logic for most applications
RedoStack.Clear();
}
public void Undo()
{
if (CanUndo)
{
ICommand command = UndoStack.Pop();
if (command != null )
{
command.Reverse();
RedoStack.Push(command);
}
}
}
public void Redo()
{
if (CanRedo)
{
ICommand command = RedoStack.Pop();
if (command != null )
{
command.Execute();
UndoStack.Push(command);
}
}
}
}
完!