/java/

Chain of Responsibility

2014-09-17 22:30:08

Main.java

package chainofresponsibility;

import chainofresponsibility.source.SourceOfMoney;

public class Main {

    public static void main(String[] args) {

        // small child need some money

        SourceOfMoney toy = new SourceOfMoney("Some Random Toy", 0);
        SourceOfMoney mom = new SourceOfMoney("Mom", 10);
        SourceOfMoney dad = new SourceOfMoney("Dad", 100);
        SourceOfMoney grandmother = new SourceOfMoney("Grandmother", 500);
        SourceOfMoney grandfather = new SourceOfMoney("Ggrandfather", 1000);

        toy.registerNext(mom);
        mom.registerNext(dad);
        dad.registerNext(grandmother);
        grandmother.registerNext(grandfather);

        System.out.println(toy.approve(101).getWhoApproved());
    }

}

ISourceOfMoney.java

package chainofresponsibility.source;

public interface ISourceOfMoney {

    void registerNext(ISourceOfMoney sourceOfMoney);

    Approval approve(int howMany);
}

SourceOfMoney.java

package chainofresponsibility.source;

public class SourceOfMoney implements ISourceOfMoney {

    private final String name;
    private final int moneyLimit;
    private ISourceOfMoney sourceOfMoney = new EndOfChainSourceOfMoney();

    public SourceOfMoney(String name, int moneyLimit) {
        this.name = name;
        this.moneyLimit = moneyLimit;
    }

    public void registerNext(ISourceOfMoney sourceOfMoney) {
        this.sourceOfMoney = sourceOfMoney;
    }

    public Approval approve(int howMany) {

        if (howMany <= moneyLimit) {
            return new Approval(name);
        }

        return sourceOfMoney.approve(howMany);
    }
}

EndOfChainSourceOfMoney.java

package chainofresponsibility.source;

public class EndOfChainSourceOfMoney implements ISourceOfMoney {

    @Override
    public void registerNext(ISourceOfMoney sourceOfMoney) {
        throw new IllegalStateException("Next is forbidden.");
    }

    @Override
    public Approval approve(int howMany) {
        return new Approval("Nobody :(");
    }
}

Approval.java

package chainofresponsibility.source;

public class Approval {

    private String whoApproved;

    public Approval(String whoApproved) {
        this.whoApproved = whoApproved;
    }

    public String getWhoApproved() {
        return whoApproved;
    }
}