[英]Chain of Responsibility: remainder algorithm?
在以下方法中,我嘗試執行以下操作:
如果您至少有20英鎊:
算出20英鎊的面額
算出剩下的(剩余)–將其傳遞給下一個處理程序
如果您的存款少於£20,請致電下一位服務員
注意:該程序適用於ATM分配器,它根據用戶需要的量(數量)分配鈔票(20、10、5)。
到目前為止,以下是我的解決方案,我需要幫助來糾正算法
@Override
public void issueNotes(int amount) {
//work out amount of twenties needed
if(amount >= 20) {
int dispenseTwenty;
int remainder;
dispenseTwenty = amount%20;
remainder = amount = //call next handler?
}
else {
//call next handler (as amount is under 20)
}
}
沒關系的語法,請參見下文:
public static final denominators = [20,10,5]
// recursive function
// you can start calling this recursive function with denom_index=0, thus using denominator 20
public void issueNotes(int amount, int denom_index)
{
int currentDenominator = denominators[denom_index];
if(amount ==0) return; // no more dispensing
if(denom_index >2) // remainder drop to below 5
{
throwException (" remaining amount not dispensable ");
}
if (amount < currentDenominator) // amount less than current denominator
{
issueNotes(amount, denom_index+1);
}
else
{
dispenseNotes(amount/currentDenominator, currentDenominator);
// call the handler with remainder of the amount and next denominator
issueNotes(amount%currentDenominator, denom_index+1);
}
}
責任鏈模式取決於能否提供行為來處理請求消息-並可能對其進行處理。 如果處理程序無法處理請求,則調用下一個封裝的處理程序
兩個核心組成部分將是界面和具體
interface IMoneyHandler {
void issueNotes(int money);
void setNext(IMoneyHandler handler);
}
具體實施的示例可能是-
class TwentyMoneyHandler implements IMoneyHandler {
private IMoneyHandler nextHandler;
@Override
public void issueNotes(int money) {
int handlingAmount = 20;
// Test if we can handle the amount appropriately, otherwise delegate it
if(money >= handlingAmount) {
int dispenseNotes = money / handlingAmount;
System.out.println(dispenseNotes + " £20s dispenses");
int remainder = money % handlingAmount;
// Propagate the information to the next handler in the chain
if(remainder > 0) {
callNext(remainder);
}
} else {
// call the next handler if we can not handle it
callNext(money);
}
}
// Attempts to call the next if there is money left
private void callNext(int remainingMoney) {
// Note, there are different ways of null handling
// IE throwing an exception, or explicitly having a last element
// in the chain which handles this scenario
if(nextHandler != null) {
nextHandler.issueNotes(remainingMoney);
}
}
@Override
public void setNext(IMoneyHandler handler) {
this.nextHandler = handler;
}
}
請注意,在現實世界中,您可能為此提供了一個抽象實現,以避免代碼重復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.