0

在以下方法中,我尝试执行以下操作:

如果您至少有 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)
    }
}
4

2 回答 2

0

责任链模式取决于能够提供处理请求消息的行为 - 并可能处理它。如果处理程序无法处理请求,它会调用下一个封装的处理程序

两个核心组件将是接口和具体

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;
    }
}

请注意,在现实世界中,您可能会为此提供抽象实现,以避免代码重复。

于 2014-03-21T15:30:00.647 回答
0

别介意语法,见下文:

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);

   }

}
于 2014-03-21T01:34:12.590 回答