Abstract Factory
// Interface representing any payment gateway
interface PaymentGate way {
void processPayment(double amount);
}
// Concrete implementation: Razorpay
class RazorpayGateway implements PaymentGateway {
@Override
public void processPayment(double amount) {
System.out.println("Processing INR payment via Razorpay: " + amount);
}
}
// Concrete implementation: PayU
class PayUGateway implements PaymentGateway {
@Override
public void processPayment(double amount) {
System.out.println("Processing INR payment via PayU: " + amount);
}
}
// Interface representing invoice generation
interface Invoice {
void generateInvoice();
}
// Concrete invoice implementation for India
class GSTInvoice implements Invoice {
@Override
public void generateInvoice() {
System.out.println("Generating GST Invoice for India.");
}
}
// CheckoutService that directly handles object creation (bad practice)
class CheckoutService {
private String gatewayType;
public CheckoutService(String gatewayType) {
// Constructor accepts a string to determine which gateway to use
this.gatewayType = gatewayType;
}
// Checkout process hardcodes logic for gateway and invoice creation
public void checkOut(double amount) {
// Hardcoded decision logic
PaymentGateway paymentGateway;
if (this.gatewayType.equals("razorpay")) {
paymentGateway = new RazorpayGateway();
} else {
paymentGateway = new PayUGateway();
}
// Process payment using selected gateway
paymentGateway.processPayment(amount);
// Always uses GSTInvoice, even though more types may exist later
Invoice invoice = new GSTInvoice();
invoice.generateInvoice();
}
}
// Main method
public class Main {
public static void main(String[] args) {
// Example: Using Razorpay
CheckoutService razorpayService = new CheckoutService("razorpay");
razorpayService.checkOut(1500.00);
}
}Class Diagram

Last updated