• 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

  • 相关阅读:
    HTML5然还在草案阶段
    简单的JS动态加载单体
    步步为营 C# 技术漫谈 五、事件与委托机制
    .NET简谈脚本引擎系列(一:认识脚本引擎)
    微软一站式示例代码库 6月再次更新14个新示例代码
    CLR(公共语言运行时)到底藏在哪?
    .NET简谈构件系统开发模式
    项目管理理论与实践系列文章索引
    .Net调试技巧
    Lucene.Net
  • 原文地址:https://www.cnblogs.com/itech/p/1727445.html
Copyright © 2020-2023  润新知