执行者类:
public class Calculator {
private int total= 0 ;
public void operation ( char operator, int operand) {
switch ( operator) {
case '+' : total+= operand; break ;
case '-' : total-= operand; break ;
case '*' : total*= operand; break ;
case '/' : total/= operand; break ;
}
System. out. println ( operator+ " " + operand+ " =" + total) ;
}
}
抽象命令类:
public abstract class Command {
public abstract void execute ( ) ;
public abstract void unexecute ( ) ;
}
计算命令类:
public class CalculatorCommand extends Command {
private Calculator calculator;
private char operator;
private int operand;
CalculatorCommand ( Calculator calculator, char operator, int operand) {
super ( ) ;
this . calculator = calculator;
this . operator = operator;
this . operand = operand;
}
public Calculator getCalculator ( ) {
return calculator;
}
public void setCalculator ( Calculator calculator) {
this . calculator = calculator;
}
public char getOperator ( ) {
return operator;
}
public void setOperator ( char operator) {
this . operator = operator;
}
public int getOperand ( ) {
return operand;
}
public void setOperand ( int operand) {
this . operand = operand;
}
@Override
public void execute ( ) {
calculator. operation ( operator, operand) ;
}
@Override
public void unexecute ( ) {
calculator. operation ( undo ( operator) , operand) ;
}
private char undo ( char operator2) {
char ch = 0 ;
switch ( operator2) {
case '+' : ch= '-' ; break ;
case '-' : ch= '+' ; break ;
case '*' : ch= '/' ; break ;
case '/' : ch= '*' ; break ;
}
return ch;
}
}
通知命令给执行者:
public class Invoker {
private Calculator calculator= new Calculator ( ) ;
private ArrayList< Command> commands= new ArrayList < Command> ( ) ;
private int current= 0 ;
public void redo ( int levels) {
System. out. println ( levels) ;
for ( int i= 0 ; i< levels; i++ ) {
if ( current< commands. size ( ) - 1 ) {
commands. get ( i) . execute ( ) ;
current++ ;
}
}
}
public void undo ( int levels) {
System. out. println ( levels) ;
for ( int i= 0 ; i< levels; i++ ) {
if ( current> 0 ) {
-- current;
commands. get ( i) . execute ( ) ;
}
}
}
public void compute ( char operator, int operand) {
Command command = new CalculatorCommand ( calculator, operator, operand) ;
command. execute ( ) ;
commands. add ( command) ;
current++ ;
}
}
客户端:
public class Client {
public static void main ( String[ ] args) {
Invoker invoker= new Invoker ( ) ;
invoker. compute ( '+' , 100 ) ;
invoker. compute ( '-' , 50 ) ;
invoker. compute ( '*' , 20 ) ;
invoker. compute ( '/' , 2 ) ;
invoker. redo ( 2 ) ;
invoker. undo ( 1 ) ;
}
}