生活随笔
收集整理的這篇文章主要介紹了
命令模式实例计算器
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
使用命令模式巖石和簡單的計算器功能,并允許執(zhí)行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
);}@Overridepublic void Execute() {cal
.Operation(op
, num
);}@Overridepublic 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
--;}
}
}
總結(jié)
以上是生活随笔為你收集整理的命令模式实例计算器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。