ACtion
类是抽象类。其中有两个功能:
doAction(int k)
按执行取款或存款
printAction()
打印执行的动作
DepositAction
并且WithdrawAction
是Action
该类的两个实现。
actionList
是一个Queue
保存最近发生的 10 笔交易。
amount
是当前账户持有的总金额,这是两个类DepositAction
和WithdrawAction
操作的数量。
希望这会帮助你。
public class BankAccount{
private int amount;
private Queue<Action> actionList=new LinkedList<Action>();
public void withDraw(int k){
Action a = new withdrawAction();
a.doAction(k);
if(actionList.size()<10){
actionList.offer(a);
}
else{
actionList.poll();
actionList.offer(a);
}
}
public void deposit(int k){
Action a = new DepositAction();
a.doAction(k);
if(actionList.size()<10){
actionList.offer(a);
}
else{
actionList.poll();
actionList.offer(a);
}
}
abstract class Action{
String actionDesc=null;
abstract void doAction(int k);
abstract void printAction();
}
class DepositAction extends Action{
@Override
void doAction(int k) {
amount=amount+k;
actionDesc="Deposit: "+k;
}
@Override
void printAction() {
System.out.println(actionDesc);
}
}
class withdrawAction extends Action{
@Override
void doAction(int k) {
if(amount-k<0){
throw new IllegalArgumentException();
}
amount=amount-k;
actionDesc="Withdraw: "+k;
}
@Override
void printAction() {
System.out.println(actionDesc);
}
}
}