首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >责任链:剩余算法?

责任链:剩余算法?
EN

Stack Overflow用户
提问于 2014-03-20 15:45:16
回答 1查看 176关注 0票数 0

在下面的方法中,我试图执行以下操作:

如果您至少有20 20:

  • 计算出国标20元的数目。
  • 计算出剩下的(剩余部分)-将其传递给下一个处理程序
  • 如果您有更少的20 20调用下一个处理程序

注意:该程序是为一个自动取款机,它分发笔记(20,10,5)取决于什么(数量)的用户需要。

下面是我的解决方案,到目前为止,我需要帮助纠正算法。

代码语言:javascript
复制
@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)
    }
}
EN

回答 1

Stack Overflow用户

发布于 2014-03-21 15:30:00

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

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

代码语言:javascript
复制
interface IMoneyHandler {
    void issueNotes(int money);
    void setNext(IMoneyHandler handler);
}

具体实施的一个例子可以是-

代码语言:javascript
复制
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;
    }
}

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22538132

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档