Bạn có một đoạn code xử lý theo nhiều loại đối tượng khác nhau bằng if hoặc switch.
Trước: dùng if-else
public class PaymentProcessor {
public double calculateFee(Payment payment) {
if (payment.getType().equals("CREDIT_CARD")) {
return payment.getAmount() * 0.02;
} else if (payment.getType().equals("BANK_TRANSFER")) {
return payment.getAmount() * 0.01;
} else if (payment.getType().equals("PAYPAL")) {
return payment.getAmount() * 0.03;
} else {
throw new IllegalArgumentException("Unknown payment type");
}
}
}
Sau: Refactor dùng Polymorphism
Bước 1: Tạo interface hoặc abstract class
public interface Payment {
double getAmount();
double calculateFee();
}
Bước 2: Tạo các lớp con cụ thể
public class CreditCardPayment implements Payment {
private double amount;
public CreditCardPayment(double amount) {
this.amount = amount;
}
public double getAmount() {
return amount;
}
public double calculateFee() {
return amount * 0.02;
}
}
public class BankTransferPayment implements Payment {
private double amount;
public BankTransferPayment(double amount) {
this.amount = amount;
}
public double getAmount() {
return amount;
}
public double calculateFee() {
return amount * 0.01;
}
}
public class PaypalPayment implements Payment {
private double amount;
public PaypalPayment(double amount) {
this.amount = amount;
}
public double getAmount() {
return amount;
}
public double calculateFee() {
return amount * 0.03;
}
}
Bước 3: Sử dụng mà không cần if hoặc switch
public class PaymentProcessor {
public double calculateFee(Payment payment) {
return payment.calculateFee();
}
}
@RestController
@RequestMapping("/api/payments")
public class PaymentController {
private final PaymentProcessor paymentProcessor;
public PaymentController(PaymentProcessor paymentProcessor) {
this.paymentProcessor = paymentProcessor;
}
@PostMapping("/calculate-fee")
public ResponseEntity<FeeResponse> calculateFee(@RequestBody PaymentRequest request) {
Payment payment = mapToPayment(request);
double fee = paymentProcessor.calculateFee(payment);
return ResponseEntity.ok(new FeeResponse(fee));
}
private Payment mapToPayment(PaymentRequest request) {
switch (request.getType()) {
case "CREDIT_CARD":
return new CreditCardPayment(request.getAmount());
case "BANK_TRANSFER":
return new BankTransferPayment(request.getAmount());
case "PAYPAL":
return new PaypalPayment(request.getAmount());
default:
throw new IllegalArgumentException("Unsupported payment type: " + request.getType());
}
}
}
Lợi ích của Polymorphism
- Code sạch hơn, không cần điều kiện phân nhánh
- Dễ mở rộng (chỉ cần thêm lớp mới, không sửa code cũ)
- Tuân thủ nguyên lý OOP: Open/Closed Principle
- Dễ test và tái sử dụng
Be First to Comment