79 lines
2.6 KiB
Java
79 lines
2.6 KiB
Java
package inventory;
|
|
|
|
import java.util.Objects;
|
|
|
|
import static inventory.ProductFactory.BOOK_TYPE;
|
|
|
|
/**
|
|
* Strategy pattern implementation for calculating different types of discounts.
|
|
* Requirements:
|
|
* - Student discount: 10% off books only
|
|
* - Bulk discount: 15% off when buying 5+ items
|
|
* - No discount option
|
|
* - Return discount amount and description
|
|
*/
|
|
public class DiscountCalculator {
|
|
|
|
/**
|
|
* @param product - the product being purchased
|
|
* @param quantity - quantity being purchased
|
|
* @param discountType - type of discount to apply (STUDENT, BULK, NONE)
|
|
* @return DiscountResult with amount and description
|
|
*/
|
|
public static DiscountResult calculateDiscount(Product product, int quantity, String discountType) {
|
|
|
|
double discountAmount = 0.0;
|
|
String description = "No discount applied";
|
|
|
|
switch (discountType.toUpperCase()) {
|
|
|
|
case "STUDENT":
|
|
if (isEligibleForStudentDiscount(product)) {
|
|
discountAmount = product.getPrice() * quantity * 0.10;
|
|
description = "Student discount: 10% off books";
|
|
} else {
|
|
description = "Student discount only applies to books";
|
|
}
|
|
break;
|
|
|
|
case "BULK":
|
|
if (isEligibleForBulkDiscount(quantity)) {
|
|
discountAmount = product.getPrice() * quantity * 0.15;
|
|
description = "Bulk discount: 15% off for 5+ items";
|
|
} else {
|
|
description = "Bulk discount requires 5+ items";
|
|
}
|
|
break;
|
|
|
|
case "EMPLOYEE":
|
|
discountAmount = product.getPrice() * quantity * 0.20;
|
|
description = "Employee discount: 20% off";
|
|
break;
|
|
|
|
case "NONE":
|
|
default:
|
|
// No discount
|
|
break;
|
|
}
|
|
|
|
return new DiscountResult(discountAmount, description);
|
|
}
|
|
|
|
private static boolean isEligibleForStudentDiscount(Product product) {
|
|
return BOOK_TYPE.equals(product.getType());
|
|
}
|
|
|
|
private static boolean isEligibleForBulkDiscount(int quantity) {
|
|
return quantity >= 5;
|
|
}
|
|
|
|
public record DiscountResult(double discountAmount, String description) {
|
|
public DiscountResult(double discountAmount, String description) {
|
|
if (discountAmount < 0) {
|
|
throw new IllegalArgumentException("Discount amount must be greater than 0");
|
|
}
|
|
this.discountAmount = discountAmount;
|
|
this.description = Objects.requireNonNullElse(description, "");
|
|
}
|
|
}
|
|
} |