场景:ATM取钱
100面额 -> 50面额 -> 20面额 -> 10面额
接口类
/**
* 取钱抽象类
*/
public interface IDrawing {
boolean draw(Integer amount);
}
面额类
import java.util.function.Function;
// 面额类
public class MoneyPile implements IDrawing {
/**
* 面额
*/
private Integer value;
/**
* 数量
*/
private Integer quantity;
/**
* 下一面额处理
*/
private IDrawing next;
public MoneyPile(Integer value, Integer quantity, IDrawing next) {
this.value = value;
this.quantity = quantity;
this.next = next;
}
@Override
public boolean draw(Integer amount) {
// 判断是否可以取
Function<Integer,Boolean> canTake = (want) -> (want / this.value) > 0;
while (canTake.apply(amount)) {
if (quantity == 0 ) break;
amount -= value;
quantity -= 1;
}
if (amount <= 0) return true;
if (next != null) return next.draw(amount);
return false;
}
}
ATM类
public class ATM implements IDrawing{
private IDrawing hundred;
private IDrawing fifty;
private IDrawing twenty;
private IDrawing ten;
private IDrawing startPile;
public ATM(IDrawing hundred, IDrawing fifty, IDrawing twenty, IDrawing ten) {
this.hundred = hundred;
this.fifty = fifty;
this.twenty = twenty;
this.ten = ten;
this.startPile = hundred;
}
@Override
public boolean draw(Integer amount) {
return startPile.draw(amount);
}
}
使用
public class Main {
public static void main(String[] args) {
MoneyPile ten = new MoneyPile(10, 2, null);
MoneyPile twenty = new MoneyPile(20, 4, ten);
MoneyPile fifty = new MoneyPile(50, 2, twenty);
MoneyPile hundred = new MoneyPile(100, 1,fifty);
ATM atm = new ATM(hundred, fifty, twenty, ten);
boolean taked = atm.draw(300);
if (taked){
System.out.println("完成");
}else {
System.out.println("ATM钱不够了");
}
}
}