Jag visar hela exemplet på vad jag menade, jag lägger ofta till undo och redo när jag skriver något program och implementeringen ser alltid ut i stil med följade kod. Jag tror det skulle passa bra in på ditt exempel:
[PHP]
public interface Action {
public void undo();
public void redo();
public void execute();
}
[/PHP]
[PHP]
import java.util.Stack;
public class ActionStack {
private Stack<Action> undoStack;
private Stack<Action> redoStack;
public ActionStack(){
undoStack = new Stack<Action>();
redoStack = new Stack<Action>();
}
public void execute(Action a){
a.execute();
undoStack.push(a);
redoStack.clear();
}
public void undo(){
Action a = undoStack.pop();
a.undo();
redoStack.push(a);
}
public void redo(){
Action a = redoStack.pop();
a.redo();
undoStack.push(a);
}
public boolean canUndo(){
return !undoStack.isEmpty();
}
public boolean canRedo(){
return !redoStack.isEmpty();
}
}
[/PHP]
Följt av 2 exempel på klasser och en körning:
[PHP]
public class AppendStringAction implements Action{
private StringBuilder sb;
private String s;
public AppendStringAction(StringBuilder sb, String s){
this.sb = sb;
this.s = s;
}
@Override
public void undo() {
sb.replace(sb.length()-s.length(), sb.length(), "");
}
@Override
public void redo() {
sb.append(s);
}
@Override
public void execute() {
sb.append(s);
}
}
[/PHP]
[PHP]
public class PrependStringAction implements Action{
private StringBuilder sb;
private String s;
public PrependStringAction(StringBuilder sb, String s){
this.sb = sb;
this.s = s;
}
@Override
public void undo() {
sb.replace(0, s.length(), "");
}
@Override
public void redo() {
sb.insert(0, s);
}
@Override
public void execute() {
sb.insert(0, s);
}
}
[/PHP]
[PHP]
public static void main(String[] args){
ActionStack as = new ActionStack();
System.out.println("Adding:");
StringBuilder sb = new StringBuilder("*");
as.execute(new AppendStringAction(sb, "2"));
as.execute(new PrependStringAction(sb, "3"));
as.execute(new AppendStringAction(sb, "4"));
as.execute(new PrependStringAction(sb, "5"));
as.execute(new AppendStringAction(sb, "6"));
as.execute(new PrependStringAction(sb, "7"));
as.execute(new AppendStringAction(sb, "8"));
as.execute(new PrependStringAction(sb, "9"));
as.execute(new AppendStringAction(sb, "8"));
as.execute(new PrependStringAction(sb, "7"));
as.execute(new AppendStringAction(sb, "6"));
as.execute(new PrependStringAction(sb, "5"));
as.execute(new PrependStringAction(sb, "4"));
as.execute(new AppendStringAction(sb, "3"));
as.execute(new PrependStringAction(sb, "2"));
as.execute(new AppendStringAction(sb, "1"));
as.execute(new PrependStringAction(sb, "0"));
System.out.println(sb);
System.out.println("Undoing:");
while (as.canUndo()){
as.undo();
System.out.println(sb);
}
}
[/PHP]
Output:
HTML-kod:
Adding:
024579753*24688631
Undoing:
24579753*24688631
24579753*2468863
4579753*2468863
4579753*246886
579753*246886
79753*246886
79753*24688
9753*24688
9753*2468
753*2468
753*246
53*246
53*24
3*24
3*2
*2
*