/**
* {@link <a href=
* "https://[Log in to view URL]"
* target= "_blank"></a>}
*
* @author itammb ( Italia Massimiliano Buscati )
* @version JDK 1.15
*
*/
class Main {
public static class Currency {
private int amount;
public Currency(int amt) {
this.amount = amt;
}
public int getAmount() {
return this.amount;
}
}
public interface DispenseChain {
void setNextChain(DispenseChain nextChain);
void dispense(Currency cur);
}
public static class Dollar50Dispenser implements DispenseChain {
private DispenseChain chain;
@Override
public void setNextChain(DispenseChain nextChain) {
this.chain = nextChain;
}
@Override
public void dispense(Currency cur) {
if (cur.getAmount() >= 50) {
// elabora la richiesta
int num = cur.getAmount() / 50;
int remainder = cur.getAmount() % 50;
System.out.println("Dispensing " + num + " 50$ note");
if (remainder != 0)
this.chain.dispense(new Currency(remainder));
} else {
// passa l'informazione al successivo handler
this.chain.dispense(cur);
}
}
}
public static class Dollar20Dispenser implements DispenseChain {
private DispenseChain chain;
@Override
public void setNextChain(DispenseChain nextChain) {
this.chain = nextChain;
}
@Override
public void dispense(Currency cur) {
if (cur.getAmount() >= 20) {
int num = cur.getAmount() / 20;
int remainder = cur.getAmount() % 20;
System.out.println("Dispensing " + num + " 20$ note");
if (remainder != 0)
this.chain.dispense(new Currency(remainder));
} else {
this.chain.dispense(cur);
}
}
}
public static class Dollar10Dispenser implements DispenseChain {
private DispenseChain chain;
@Override
public void setNextChain(DispenseChain nextChain) {
this.chain = nextChain;
}
@Override
public void dispense(Currency cur) {
if (cur.getAmount() >= 10) {
int num = cur.getAmount() / 10;
int remainder = cur.getAmount() % 10;
System.out.println("Dispensing " + num + " 10$ note");
if (remainder != 0)
this.chain.dispense(new Currency(remainder));
} else {
this.chain.dispense(cur);
}
}
}
public static class ATMDispenseChain {
private DispenseChain c1;
public ATMDispenseChain() {
// inizializza la catena
this.c1 = new Dollar50Dispenser();
DispenseChain c2 = new Dollar20Dispenser();
DispenseChain c3 = new Dollar10Dispenser();
// configura la catena delle responsabilità
c1.setNextChain(c2);
c2.setNextChain(c3);
}
}
public static void main(String args[]) {
// Unit test - uso del design pattern: chain of responsibility
ATMDispenseChain atmDispenser = new ATMDispenseChain();
int amount = 60;
while (true) {
System.out.println("amount to dispense: " + amount);
if (amount % 10 != 0) {
System.out.println("Amount should be in multiple of 10s.");
return;
}
// processa la richiesta a partire da uno dei gestore a seguire lungo la catena
atmDispenser.c1.dispense(new Currency(amount));
amount--;
}
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: