-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPurchaseProduct.java
66 lines (55 loc) · 1.88 KB
/
PurchaseProduct.java
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
package behavioral.strategy;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class PurchaseProduct {
private final Double totalAmount;
private final List<PaymentEntry> payments;
public PurchaseProduct(Double totalAmount) {
this.totalAmount = totalAmount;
this.payments = new ArrayList<>();
}
public void pay(PaymentStrategy paymentStrategy, double amount) {
if (Objects.nonNull(paymentStrategy)) {
if (amount <= this.remaining()) {
PaymentEntry paymentEntry = new PaymentEntry(paymentStrategy, amount);
paymentEntry.doPayment();
payments.add(paymentEntry);
if (!paymentEntry.isSucceed()) {
Main.errPrintln("Payment failed");
}
} else {
Main.errPrintln("Payment must be less than remaining amount");
}
} else {
Main.errPrintln("Payment strategy not set");
}
if (this.isPurchased()) {
Main.println("Purchase completed");
}
}
public Double paid() {
return this.payments
.stream()
.filter(PaymentEntry::isSucceed)
.map(PaymentEntry::getAmount)
.mapToDouble(Double::valueOf)
.sum();
}
public Double remaining() {
return this.totalAmount - this.paid();
}
public Boolean isPurchased() {
return this.remaining() == 0;
}
@Override
public String toString() {
String purchase = this.isPurchased() ? "Purchase completed" : "Purchase remaining";
return "PurchaseProduct{" +
"totalAmount=" + this.totalAmount +
", paid=" + this.paid() +
", remaining=" + this.remaining() +
", " + purchase +
'}';
}
}