Understand Design Pattern With Example: Strategy Pattern

AM
2 min readJan 20, 2024

--

Java Design Pattern: Strategy Pattern

Unsplash -kellysikkema

The Strategy Pattern is a behavioural design pattern that defines a family of algorithms, encapsulates each algorithm, and makes them interchangeable. It allows the client to choose an algorithm at runtime. In Java, this pattern is typically implemented using interfaces and concrete classes. The Strategy Pattern is beneficial when you have a family of algorithms and want to allow the client to choose among them dynamically.

Let’s consider an example where we have a PaymentProcessor class that needs to support multiple payment methods (e.g., credit card, PayPal).

// PaymentStrategy.java
public interface PaymentStrategy {
void processPayment(double amount);
}
// CreditCardPayment.java
public class CreditCardPayment implements PaymentStrategy {
private String cardNumber;
private String name;

public CreditCardPayment(String cardNumber, String name) {
this.cardNumber = cardNumber;
this.name = name;
}
@Override
public void processPayment(double amount) {
// Implementation for credit card payment
System.out.println("Processing credit card payment of $" + amount + " using card number " + cardNumber);
}
}
// PayPalPayment.java
public class PayPalPayment implements PaymentStrategy {
private String email;

public PayPalPayment(String email) {
this.email = email;
}
@Override
public void processPayment(double amount) {
// Implementation for PayPal payment
System.out.println("Processing PayPal payment of $" + amount + " to email " + email);
}
}
// PaymentProcessor.java
public class PaymentProcessor {
private PaymentStrategy paymentStrategy;
public PaymentProcessor(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public void processPayment(double amount) {
paymentStrategy.processPayment(amount);
}
}
public class Client {
public static void main(String[] args) {
// Client can choose the payment method dynamically
PaymentStrategy creditCardPayment = new CreditCardPayment("1234-5678-9012-3456", "John Doe");
PaymentProcessor paymentProcessor = new PaymentProcessor(creditCardPayment);

paymentProcessor.processPayment(100.0);
// Change payment method dynamically
PaymentStrategy payPalPayment = new PayPalPayment("john.doe@example.com");
paymentProcessor.setPaymentStrategy(payPalPayment);
paymentProcessor.processPayment(50.0);
}
}

In this example, the PaymentProcessor class acts as the context, and it has a reference to the PaymentStrategy interface. Concrete payment strategies (CreditCardPayment and PayPalPayment) implement the PaymentStrategy interface. The client can dynamically choose and change the payment method at runtime.

Stay in the loop — follow my Medium blog for more insights and updates: [follow].

--

--