Flexibility and extensibility are often key objectives when designing systems that handle varied business requirements. Payment processing system often requires the ability to support multiple payment types while accommodating future additions or modifications with ease.
Strategy pattern: Encapsulate various payment processing algorithms (such as Cash processing, Local Transfer processing, etc.) into separate classes (strategies) that implement a common interface (PaymentProcessor). This allows the system to dynamically select and execute the appropriate algorithm based on the transaction type, promoting flexibility and maintainability in the payment processing logic.
Let's start by creating an enum with supported payment types.
Now, in the service class, inject all the processor implementation and fetch and trigger appropriate processor logic based on Transaction/Payment Type.
@RequiredArgsConstructor@ServicepublicclassPaymentService {privatefinalMap<String,PaymentProcessor> paymentProcessorMap;publicvoidprocessPayment(Transaction transaction) {// Get the payment processor based on Payment TypePaymentProcessor processor =paymentProcessorMap.get(transaction.getType().getValue());// Process the paymentprocessor.processor(transaction); }}
We can create Controller class and define the sample endpoint.