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

一連の責任パターンは、要求メッセージを処理するための動作を提供できるかどうか、および潜在的にそれを処理できるかにかかっています。ハンドラがリクエストを処理できない場合、代わりに次のカプセル化されたハンドラを呼び出します

2 つのコア コンポーネントは、インターフェイスと具象です。

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 に答える