-
Notifications
You must be signed in to change notification settings - Fork 351
Expand file tree
/
Copy pathVendingMachineController.java
More file actions
85 lines (72 loc) · 2.71 KB
/
Copy pathVendingMachineController.java
File metadata and controls
85 lines (72 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package vendingmachine.controller;
import java.util.function.Supplier;
import vendingmachine.dto.ChangeDto;
import vendingmachine.exception.IllegalArgumentBaseException;
import vendingmachine.model.Amount;
import vendingmachine.model.Change;
import vendingmachine.model.MachineAmount;
import vendingmachine.model.Order;
import vendingmachine.model.Products;
import vendingmachine.model.VendingMachine;
import vendingmachine.service.VendingMachineService;
import vendingmachine.view.InputView;
import vendingmachine.view.OutputView;
public class VendingMachineController {
private final InputView inputView = new InputView();
private final OutputView outputView = new OutputView();
private VendingMachineService vendingMachineService;
public void run() {
Change change = handleInput(this::inputMachineAmount);
outputView.printMachineState(new ChangeDto(change));
Products products = handleInput(this::inputProducts);
Amount amount = handleInput(this::inputAmount);
vendingMachineService = new VendingMachineService(new VendingMachine(change, products, amount));
buy();
}
private void buy() {
while(vendingMachineService.isBuyable()) {
buyProduct();
}
printResultChange();
}
private void printResultChange() {
outputView.printRemainAmount(vendingMachineService.getAmount());
outputView.printChange(vendingMachineService.getChange());
}
private void buyProduct() {
outputView.printRemainAmount(vendingMachineService.getAmount());
handleInput(() -> vendingMachineService.buy(inputOrder()));
}
private Order inputOrder() {
return Parser.parseOrder(inputView.inputBuyProductName());
}
private Amount inputAmount() {
return Parser.parseAmount(inputView.inputBuyAmount());
}
private Change inputMachineAmount() {
MachineAmount amount = Parser.parseMachineAmount(inputView.inputMachineAmount());
return new Change(amount);
}
private Products inputProducts() {
return Parser.parseProducts(inputView.inputProducts());
}
private <T> T handleInput(Supplier<T> inputSupplier) {
while (true) {
try {
return inputSupplier.get();
} catch (IllegalArgumentBaseException exception) {
outputView.printErrorMessage(exception.getMessage());
}
}
}
private void handleInput(Runnable runnable) {
while (true) {
try {
runnable.run();
return;
} catch (IllegalArgumentBaseException exception) {
outputView.printErrorMessage(exception.getMessage());
}
}
}
}