ZipCloudBank's meh banking app.

CashMachine.java 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //import rocks.zipcode.atm.bank.AccountData;
  2. //import rocks.zipcode.atm.bank.Bank;
  3. import java.util.function.Consumer;
  4. import java.util.function.Supplier;
  5. /**
  6. * @author ZipCodeWilmington
  7. */
  8. public class CashMachine {
  9. private final Bank bank;
  10. private AccountData accountData = null;
  11. public CashMachine(Bank bank) {
  12. this.bank = bank;
  13. }
  14. private Consumer<AccountData> update = data -> {
  15. accountData = data;
  16. };
  17. public void login(int id) {
  18. tryCall(
  19. () -> bank.getAccountById(id),
  20. update
  21. );
  22. }
  23. public void deposit(int amount) {
  24. if (accountData != null) {
  25. tryCall(
  26. () -> bank.deposit(accountData, amount),
  27. update
  28. );
  29. }
  30. }
  31. public void withdraw(int amount) {
  32. if (accountData != null) {
  33. tryCall(
  34. () -> bank.withdraw(accountData, amount),
  35. update
  36. );
  37. }
  38. }
  39. public void exit() {
  40. if (accountData != null) {
  41. accountData = null;
  42. }
  43. }
  44. @Override
  45. public String toString() {
  46. return accountData != null ? accountData.toString() : "Try account 1000 or 2000 and click submit.";
  47. }
  48. private <T> void tryCall(Supplier<ActionResult<T> > action, Consumer<T> postAction) {
  49. try {
  50. ActionResult<T> result = action.get();
  51. if (result.isSuccess()) {
  52. T data = result.getData();
  53. postAction.accept(data);
  54. } else {
  55. String errorMessage = result.getErrorMessage();
  56. throw new RuntimeException(errorMessage);
  57. }
  58. } catch (Exception e) {
  59. System.out.println("Error: " + e.getMessage());
  60. }
  61. }
  62. }