Sunday, July 17, 2011

UNDO-REDO Mechanism

UNDO-REDO mechanism works based upon Command Design Pattern that is we define a set of commands that can be executed and un-executed. Actually, execution does some task and it may contain several steps. The un-execution performs in opposite way to take to a state before execution was called.

While doing an action, command for that action is executed and since this action can be undone so, the command is put in the list of undo commands. When an undo command is executed, the task should be unexecuted and this task can be redone, so it is put in the list of redo commands. One thing to note here is, after we undo and then perform a task, then we can not redo, so in such case, the redo command lists are cleared.

To implement undo-redo, we first of all need to create the commands which are capable of executing and unexecuting the commands. To simplify, we define an interface which has the methods execute() and unexecute():

public interface Icommand{
/* Executes */
public void execute();
/* Unexecutes */
public void unExecute();


Then we define the actual command implementing this interface. The actual tasks performed by the command are defined inside the implemented command. This is done as follows:

public class AddButtonCommand implements ICommand {
public void execute(){//Define here}

public void unExecute(){//Define here}

After we define the required commands, we define a manager class which stores the history of the undo and redo commands and manages them. A sample manager class looks like this:

public class UndoredoManager {
//Undo commands list
private Stack undoList=null;
//Redo commands list
private Stack redoList=null;
public void undo(){//execute undo command}
public void redo(){//Execute redo command}
public void addCommand(ICommand command){//new command}

The above undo-redo manager class keeps track of the command list of undo and redo, and executes the command upon request. The list management through stack is appropriate for undo and redo because recently added undo command is used while redoing.

No comments:

Post a Comment