how to implement undo/redo operation without major changes in program

前端 未结 3 1025
青春惊慌失措
青春惊慌失措 2020-12-30 09:23

Hi I\'m about to add new functionality to application which I\'m currently writting. I need to write a undo/redo fnctionality. However 90% of our application is ready and I

相关标签:
3条回答
  • 2020-12-30 09:48

    As Reed Copsey says the most common pattern to implementing do/redo is Command Pattern. The basic idea is to implement actions as commands that implemets some interface like this:

    public interface ICommand  { public void Execute(); public void Undo(); }
    

    Then You have a class (Control) that executes all the commands as a whole, such class must be composed by a group of commands, the when you execute the commands each command is pushed inside a Stack (by means the push() method), in the case you want to undo the actions then you take every element from the Stack (by means of pop() ) an executes its Undo() method.

    public class Control {  
        private ArrayList<ICommand> commands  = new ArrayList<ICommand>();  
        private Stack<ICommand> stack = new Stack<ICommand>();  
    
        public Control() {      
            commands.add(new Command1());
            commands.add(new Command2());       
            commands.add(new Command3());       
        }
    
        public void Execute() {
            for(int index=0; index<=command.size(); index++) { command.Execute(); stack.push(command);}
        }
        public void Undo() 
        {
            while (!stack.empty()) {
                ICommand command = (ICommand)stack.pop();
                if (command != null) { command.Undo(); }        
            }       
        }   
    }
    

    Note: this is a very simple code, only for trying to clarify the ideas behind the Command Pattern.

    link text

    0 讨论(0)
  • 2020-12-30 10:01

    There aren't many details here. However, Undo/Redo functionality is typically handled via some variation of the Command Pattern. Depending on your architecture, this could be a simple reworking of your basic functionality into "commands", or a major overhaul.

    0 讨论(0)
  • 2020-12-30 10:06

    There's a free library written by Rockford Lhotka for Business Objects that includes built in undo/redo functionality. I think he even implements it through an interface, so it should be "minimally invasive".

    0 讨论(0)
提交回复
热议问题