命令模式undo/redo实例计算器
程序员文章站
2022-05-24 23:50:16
...
package JiSuan;
public class Caculator {
private int total;
public Caculator() {
this.total = 0;
}
public void Operation(char op,int num)
{switch(op)
{case '+':total+=num;break;
case '-':total-=num;break;
case '*':total*=num;break;
case '/':total/=num;break;
}
System.out.println(op+" "+num+"="+total);
}
}
package JiSuan;
public abstract class Command {
protected Caculator cal;
protected char op;;
protected int num;
public Command(Caculator cal, char op, int num) {
this.cal = cal;
this.op = op;
this.num = num;
}
public abstract void Execute();
public abstract void UnExecute();
}
package JiSuan;
public class CalCommand extends Command {
public CalCommand(Caculator cal, char op, int num) {
super(cal, op, num);
}
@Override
public void Execute() {
cal.Operation(op, num);
}
@Override
public void UnExecute() {
cal.Operation(undo(op), num);
}
private char undo(char op)
{char undo=' ';
switch(op)
{case '+':undo='-';break;
case '-':undo='+'; break;
case '*':undo='/';break;
case '/': undo='*'; break;
}
return undo;
}
}
package JiSuan;
import java.util.ArrayList;
public class User {
private ArrayList<Command>commands=new ArrayList<Command>();
private int count=0;
public void Compute(Command command)
{command.Execute();
count++;
commands.add(command);
}
public void Redo(int levels)
{for(int i=0;i<levels;i++)
{if(count<commands.size())
{count++;
commands.get(count-1).Execute();
}
}
}
public void Undo(int levels)
{for(int i=0;i<levels;i++)
if(count>0)
{
commands.get(count-1).UnExecute();
count--;
}
}
}