Skip to main content

The Factory

Updated 2 min readMarkdown
Part of seriesDesign Pattern
The Factory

Suppose you want to add a payment feature to your e-commerce website. You have multiple payment gateways, such as bKash and Nagad. A user selects a payment gateway from the front end and submits the payment request, which is then processed through the selected gateway.

However, as your application grows, you may need to integrate more payment gateways. If the logic for creating and handling every payment gateway is written inside a single payment service class, the code can become complicated and difficult to maintain. You might end up using multiple if-else statements to determine which payment gateway object should be created and executed.

For example, if a user selects bKash, the application creates a bKash payment object. If the user selects Nagad, it creates a Nagad payment object. If all this object-creation logic is handled by the same service class, adding new payment gateways can make that class increasingly complex.

The Factory Design Pattern helps solve this problem by separating object-creation logic from the main business logic.

Basic Rules of the Factory Design Pattern

  1. Define an interface: Create an interface that specifies the common behavior expected from all payment gateways.

  2. Implement the interface: Each payment gateway class implements the interface.

  3. Encapsulate gateway-specific logic: Each class contains its own payment-processing logic. For example, the bKash class handles bKash-specific operations, while the Nagad class handles Nagad-specific operations.

  4. Create a factory: The factory is responsible for creating and returning the appropriate payment gateway object based on the selected gateway.

As a result, the main payment service can work with the common interface instead of directly depending on individual payment gateway classes. This makes the code easier to organize, maintain, and extend.

Main Interface

public interface Payment {
    
    public void pay(double amount, String sender , String receiver);
    
}

Bkash Payment

public class BkashPayment implements Payment {

    @Override
    public void pay(double amount, String sender, String receiver){
    System.out.println("Payment completed via Bkash");

}

}

Nagad Payment

public class NagadPayment implements Payment {

    @Override
    public void pay(double amount, String sender, String receiver){
    System.out.println("Payment completed via Nagad");

}

}

Payment Factory

public class PaymentFactory {

    public Payment createPayment(String type){
        
        if (type.equals('bkash')){

            return new BkashPayment ();
        }

        else if(type.equals('nagad')){

            return new NagadPayment();
        }
        
        throw new IllegalArgumentException();

    }

}

6 views

No comments yet. Be the first to comment.