Showing posts with label Payment Gateway. Show all posts
Showing posts with label Payment Gateway. Show all posts

Monday, 30 December 2013

Strategy Design pattern - Implementation [Payment]

Want to Master Java Design Patterns?

Subscribe to Ram N Java for clean code walkthroughs and real-world architectures!

Subscribe on YouTube

Why Use Strategy Pattern in Payment Processing?

E-commerce and billing systems require support for diverse payment methods such as Credit Card, PayPal, and UPI / Net Banking.

Instead of writing messy if-else or switch blocks within a shopping cart or checkout service, the Strategy Design Pattern enables you to encapsulate each payment gateway into its own dedicated class.

Key Advantages of This Approach

  • Open/Closed Principle: Add new payment modes (e.g., Apple Pay, Crypto) without modifying existing checkout code.
  • Loose Coupling: The checkout component does not care how individual payments are authorized.
  • Runtime Flexibility: Customers can freely change their payment choice right at checkout.

Core Architecture Elements

  • PaymentStrategy (Interface): Declares the common method signature (e.g., pay(int amount)).
  • Concrete Strategies: Implementation classes such as CreditCardStrategy and PaypalStrategy.
  • ShoppingCart / PaymentContext: Maintains a reference to the selected PaymentStrategy and initiates payment processing.

Java Code Implementation

1. Define the Strategy Interface:

public interface PaymentStrategy {
    public void pay(int amount);
}

2. Create Concrete Implementations:

public class CreditCardStrategy implements PaymentStrategy {
    private String cardNumber;

    public CreditCardStrategy(String cardNumber) {
        this.cardNumber = cardNumber;
    }

    @Override
    public void pay(int amount) {
        System.out.println("Paid " + amount + " using Credit Card.");
    }
}

3. Configure the Context:

public class ShoppingCart {
    private PaymentStrategy paymentStrategy;

    public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }

    public void checkout(int amount) {
        paymentStrategy.pay(amount);
    }
}

Related Design Pattern Tutorials to Watch Next


Click here to watch in Youtube : https://www.youtube.com/watch?v=o-rSyfmBqh0

Click the below Image to Enlarge
Strategy Design pattern - Implementation [Payment]
Strategy Design pattern - Implementation [Payment] - Class Diagram




































PaymentStrategy.java

public interface PaymentStrategy
{
public void pay(String amount);

}


DebitCardPaymentStrategy.java

public class DebitCardPaymentStrategy implements PaymentStrategy
{

public void pay(String amount)
{
System.out.println("Customer pays the money " +amount+ "Rs. using Debit Card");
}

}

CreditCardPaymentStrategy.java

public class CreditCardPaymentStrategy implements PaymentStrategy
{

public void pay( String amount )
{
System.out.println("Customer pays the money " + amount + "Rs. using Credit Card");
}

}

ByCashPaymentStrategy.java

public class ByCashPaymentStrategy implements PaymentStrategy
{

public void pay( String amount )
{
System.out.println("Customer pays the money " + amount + "Rs. as a Cash");
}

}


PaymentContext.java

public class PaymentContext
{
private PaymentStrategy paymentStrategy;

// Client will set what PaymentStrategy to use by calling this method
public void setPaymentStrategy(PaymentStrategy strategy)
{
this.paymentStrategy = strategy;
}

public PaymentStrategy getPaymentStrategy()
{
return paymentStrategy;
}

public void pay(String amount)
{
paymentStrategy.pay(amount);
}

}


Customer.java

import java.util.Scanner;

public class Customer
{

public static void main( String[] args )
{

System.out.println("Please enter Payment Type : 'CreditCard' or 'DebitCard' or 'ByCash'");
Scanner scanner = new Scanner(System.in);
String paymentType = scanner.next();
System.out.println("Payment type is : " + paymentType);

System.out.println("\nPlease enter Amount to Pay : ");
Scanner scanner1 = new Scanner(System.in);
String amount = scanner1.next();
System.out.println("amount is : " + amount);

PaymentContext ctx = null;
ctx = new PaymentContext();

if( "CreditCard".equalsIgnoreCase(paymentType) )
{
ctx.setPaymentStrategy(new CreditCardPaymentStrategy());
}
else if( "DebitCard".equalsIgnoreCase(paymentType) )
{
ctx.setPaymentStrategy(new DebitCardPaymentStrategy());
}
else if( "ByCash".equalsIgnoreCase(paymentType) )
{
ctx.setPaymentStrategy(new ByCashPaymentStrategy());
}

System.out.println("PaymentContext has :"+ctx.getPaymentStrategy());

ctx.pay(amount);

}
}

Output

Please enter Payment Type : 'CreditCard' or 'DebitCard' or 'ByCash'
CreditCard
Payment type is : CreditCard

Please enter Amount to Pay :
90000
amount is : 90000
PaymentContext has :CreditCardPaymentStrategy@1e4cbc4
Customer pays the money 90000Rs. using Credit Card


Please enter Payment Type : 'CreditCard' or 'DebitCard' or 'ByCash'
DebitCard
Payment type is : DebitCard

Please enter Amount to Pay :
90000
amount is : 90000
PaymentContext has :DebitCardPaymentStrategy@1e4cbc4
Customer pays the money 90000Rs. using Debit Card


See also:



  • Strategy Design pattern - Introduction
  • Strategy Design pattern - Real Time Example [Compress files]
  • Strategy Design pattern - Real Time Example [Payment]
  • Strategy Design pattern - Real Time Example [Travel]
  • Strategy Design pattern - Real Time Example [Sorting]
  • Strategy Design pattern - Real Time Example [Search]
  • Strategy Design pattern - Class Diagram
  • Strategy Design pattern - Sequence Diagram
  • Strategy Design pattern - Implementation [Compress files]
  • Strategy Design pattern - Implementation [Travel]
  • Strategy Design pattern - Implementation [Search]
  • Strategy Design pattern - Implementation [Sort]
  • Strategy Design pattern - KeyPoints
  • All Design Patterns Links
  • Friday, 27 December 2013

    Strategy Design pattern - Real Time Example [Payment]

    Want to Master Java Design Patterns?

    Subscribe to Ram N Java for clean code, architecture patterns, and practical Java tutorials!

    Subscribe on YouTube

    The Real-World Payment Dilemma

    In any modern e-commerce or point-of-sale system, customers demand multiple payment methods at checkout. Whether it is a Credit Card, PayPal, or digital wallets like UPI, each method handles authorization and fee structures completely differently.

    Hardcoding payment choices with huge if-else or switch blocks makes checkout code fragile and tough to maintain. The Strategy Design Pattern solves this by turning every payment option into an interchangeable strategy object.

    How the Strategy Pattern Fits Payment Gateways

    The Strategy pattern defines a family of algorithms or business rules, encapsulates each one inside a separate class, and lets clients select them at runtime:

    • Strategy Interface: Defines a standard contract such as pay(int amount) shared by every payment mechanism.
    • Concrete Strategy Classes: Independent classes like CreditCardStrategy and PayPalStrategy encapsulating specific payment provider logic.
    • Context (Shopping Cart): Holds a reference to the active payment strategy and triggers checkout without caring about provider-specific details.

    Key Architectural Benefits

    Adopting this design pattern yields major advantages:

    • Open/Closed Principle: Add new payment options like Google Pay or Cryptocurrency without modifying the existing checkout service.
    • Separation of Concerns: The shopping cart handles items and totals, while strategies handle authentication and transactions.
    • Runtime Flexibility: Shoppers can switch their preferred payment method instantly right at the checkout counter.

    Related Design Pattern Tutorials to Watch Next


    Click here to watch in Youtube : https://www.youtube.com/watch?v=VJHXpxrskCE

    Click the below Image to Enlarge
    Strategy Design pattern - Real Time Example [Payment]


















    See also:

  • Strategy Design pattern - Introduction
  • Strategy Design pattern - Real Time Example [Compress files]
  • Strategy Design pattern - Real Time Example [Travel]
  • Strategy Design pattern - Real Time Example [Sorting]
  • Strategy Design pattern - Real Time Example [Search]
  • Strategy Design pattern - Class Diagram
  • Strategy Design pattern - Sequence Diagram
  • Strategy Design pattern - Implementation [Compress files]
  • Strategy Design pattern - Implementation [Travel]
  • Strategy Design pattern - Implementation [Payment]
  • Strategy Design pattern - Implementation [Search]
  • Strategy Design pattern - Implementation [Sort]
  • Strategy Design pattern - KeyPoints
  • All Design Patterns Links
  • Tutorials