命令模式实例计算器
使用命令模式岩石和简单的计算器功能,并允许执行UNDO和REDO
UML图
代码
package 命令模式;
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 命令模式;
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 命令模式;
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 命令模式;
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--;
}
}
}