现在的位置: 首页 > 综合 > 正文

Undo/Redo实现

2017年11月01日 ⁄ 综合 ⁄ 共 1487字 ⁄ 字号 评论关闭

 

一 使用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);
        }        
      }
    }
}

 

 

完!

 

【上篇】
【下篇】

抱歉!评论已关闭.