Provide a Do, Undo, Redo command pattern solution that can assist a workflow
application.

This is simple.  Here are the basic classes and then I will give the application
itself, which is fairly straightforward.


// COMMAND CLASS
public interface Command {
  public void doCommand();
  public void undoCommand();
}

// Do, Undo, and Redo COMMANDS
public interface Do extends Command {}

public final class Undo implements Command {
  public void doCommand() { return; }
  public void undoCommand() { return; }
}

public final class Redo implements Command {
  public void doCommand() { return; }
  public void undoCommand() { return; }
}
The following is the application class:

public class UndoableList {
  private int       maxHistory = 100;
  private LinkedList   history = new LinkedList();
  private LinkedList  redoList = new LinkedList();

  private UndoableList() {
  }

  public static UndoableList getInstance() {
  return new UndoableList();
  }

  public void setMaxHistory(int maxHistory) {
    this.maxHistory = maxHistory;
  }

  public void invoke(Command command) {
    if (command instanceof Undo) { undoCommand(); return; }
    if (command instanceof Redo) { redoCommand(); return; }

    if (command instanceof Do) {
      command.doCommand();
      addToHistory(command);
    } else {
      history.clear();
    }

    if (redoList.size() > 0) {
      redoList.clear();
    }
  }

  private void undoCommand() {
    if (history.size() > 0) {
      Command undoCommand = (Command)history.removeFirst();
      undoCommand.undoCommand();
      redoList.addFirst(undoCommand);
    }
  }

  private void redoCommand() {
    if (redoList.size() > 0) {
      Command redoCommand = (Command)redoList.removeFirst();
      redoCommand.doCommand();
      history.addFirst(redoCommand);
    }
  }

  private void addToHistory(Command command) {
    history.addFirst(command);
    if (history.size() > maxHistory) {
      history.removeLast();
    }
  }
}
You can clearly add to this or change this in a myriad of ways. Enjoy! Michael !McGrady