Undo/Redo实现

一 使用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 { getprotected set; }
    
public Stack<ICommand> RedoStack { getprotected set; }

    
public bool CanUndo { get { return UndoCommands.Count > 0; } }
    
public bool CanRedo { get { return RedoCommands.Count > 0; } }


    
public void Execute(ICommand command)
    {
      
if (command == nullreturn;
      
// 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);
        }        
      }
    }
}

完!


作者:iTech
微信公众号: cicdops
出处:http://itech.cnblogs.com/
github:https://github.com/cicdops/cicdops

原文地址:https://www.cnblogs.com/itech/p/1727445.html