Strategy Design Pattern
The Strategy Design Pattern is a behavioral
pattern that allows you to define a family of algorithms, put each of them
in a separate class, and make them interchangeable at runtime.
Use Case: Payment Strategy
Example Scenario: Payment System
Imagine an e-commerce app where customers can choose
how to pay:
- Credit
card
- PayPal
- UPI
Instead of hardcoding multiple if-else or switch statements,
use Strategy Pattern to plug in different payment behaviors.
This keeps code flexible, maintainable, and scalable.
Key Components
- Strategy
Interface
- Declares
a common method that all concrete strategies must implement.
- Concrete
Strategies
- Implement
different versions of the algorithm.
- Context
- Uses
a strategy object and delegates it the task of executing the algorithm.
UML Diagram
Example
Strategy Interface
package stratgydesignpattern;
public interface PaymentStrategy {
void pay(double amount);
}
Concrete Strategy Classes
package stratgydesignpattern;
public class CreditCardPayment implements PaymentStrategy {
private
String cardNumber;
private
String cardHolder;
public
CreditCardPayment(String cardNumber, String cardHolder) {
super();
this.cardNumber
= cardNumber;
this.cardHolder
= cardHolder;
}
@Override
public void
pay(double amount) {
System.out.println("Paid
₹" + amount + " using Credit Card.");
}
}
package stratgydesignpattern;
public class PayPalPayment implements PaymentStrategy {
private
String email;
public
PayPalPayment(String email) {
super();
this.email
= email;
}
@Override
public void
pay(double amount) {
System.out.println("Paid
₹" + amount + " using PayPal.");
}
}
package stratgydesignpattern;
public class UpiPayment implements PaymentStrategy {
private
String upiId;
public
UpiPayment(String upiId) {
this.upiId
= upiId;
}
@Override
public void
pay(double amount) {
System.out.println("Paid
₹" + amount + " using UPI.");
}
}
Context Class
package stratgydesignpattern;
public class PaymentContext {
private
PaymentStrategy paymentStrategy;
public void
setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy
= paymentStrategy;
}
public void
payAmount(double amount) {
if
(paymentStrategy == null) {
System.out.println("Payment
strategy not set!");
return;
}
paymentStrategy.pay(amount);
}
}
Client Code
package stratgydesignpattern;
public class Cient {
public
static void main(String[] args) {
PaymentContext
paymentContext = new PaymentContext();
paymentContext.setPaymentStrategy(new
CreditCardPayment("123456789", "Govind Khan"));
paymentContext.payAmount(1000);
paymentContext.setPaymentStrategy(new
PayPalPayment("govindkhan@gmail.com"));
paymentContext.payAmount(800);
paymentContext.setPaymentStrategy(new
UpiPayment("govind@upi"));
paymentContext.payAmount(500);
}
}
o/p :-
Paid ₹1000.0 using Credit Card.
Paid ₹800.0 using PayPal.
Paid ₹500.0 using UPI.
Use Cases in Java (Real-World Examples)
✅ 1. Sorting Algorithms in Java
Java’s Collections.sort() method uses Strategy Pattern
internally.
List<Employee> employees = new ArrayList<>();
Collections.sort(employees, new SalaryComparator());
- Comparator<T>
is the strategy interface
- SalaryComparator,
NameComparator are concrete strategies
✅ 2. Java Streams
list.stream().sorted(Comparator.comparing(Employee::getName));
- Comparator
is a strategy
- You
can pass different sorting strategies dynamically
✅ 3. Java Swing / GUI Frameworks
Swing uses Strategy pattern in layout managers.
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout()); // or new GridLayout()
Each layout (Flow, Grid, Border) is a different strategy
for arranging UI components.
✅ 4. Spring Framework
- Spring
Security uses Strategy pattern for authentication and authorization
mechanisms.
- Spring
Boot uses strategy pattern for logging, error handling, and data
serialization by letting you plug in different implementations.
Example:
AuthenticationManager authManager = new ProviderManager(List.of(new
DaoAuthenticationProvider()));
🔧 Benefits of Strategy
Pattern
Benefit |
Description |
Open/Closed Principle |
Add new strategies without modifying existing code. |
Decoupling |
Decouple behavior from context (class using it). |
Runtime Flexibility |
Switch algorithms at runtime. |
⚠️ When Not to Use
- If
the behavior doesn’t change or is unlikely to vary.
- When
adding too many strategies would make the code more complex than
necessary.
🔚 Summary
- Strategy
Pattern is perfect when you have multiple ways of doing something, like
different payment options, sorting methods, or layout managers.
- Java's
standard libraries and frameworks like Collections, Streams, Swing, and Spring
make heavy use of it.
- It
improves flexibility, reusability, and clean separation of concerns.
No comments:
Post a Comment