Strategy Design Pattern in Java
Learn Strategy Design Pattern in Java with runtime algorithm selection, payment processing, discount calculation, Spring Security strategies, UML diagrams, Java implementation, enterprise use cases, and interview questions.
What You Will Learn
- What is Strategy Pattern?
- Why Strategy Pattern is Needed
- Runtime Algorithm Selection
- Payment Processing Example
- Discount Calculation Example
- Java Implementation
- Spring Security Examples
- Enterprise Use Cases
- Benefits and Limitations
- Interview Questions
Introduction
Many enterprise applications support multiple ways of performing the same task.
Examples:
Credit Card Payment
UPI Payment
PayPal Payment
Apple Pay
Or:
Regular Customer Discount
Premium Customer Discount
Gold Customer Discount
Or:
Password Authentication
OAuth Authentication
Biometric Authentication
Without Strategy Pattern:
if(type.equals("CREDIT_CARD")) {
}
else if(type.equals("PAYPAL")) {
}
else if(type.equals("UPI")) {
}
As new options grow:
Code Becomes Huge
Hard To Maintain
Violates Open Closed Principle
Strategy Pattern solves this problem.
What is Strategy Pattern?
Strategy is a Behavioral Design Pattern that defines a family of algorithms, encapsulates each one, and makes them interchangeable.
Simple View:
Context
↓
Strategy
↓
Algorithm
The algorithm can change at runtime.
Purpose of Strategy Pattern
Primary Goal:
Replace Large If Else Blocks
With Interchangeable Algorithms
Real World Analogy
Navigation Apps.
You enter:
San Antonio → Dallas
Possible strategies:
Fastest Route
Shortest Route
No Toll Route
Scenic Route
The destination is same.
Strategy changes.
Problem Without Strategy
flowchart LR
A[Client]
B[Credit Card Logic]
C[PayPal Logic]
D[UPI Logic]
A --> B
A --> C
A --> D
Client depends on every implementation.
Solution With Strategy
flowchart LR
A[Client]
B[Payment Strategy]
A --> B
Client only knows strategy interface.
Strategy Architecture
flowchart LR
A[Context]
B[Strategy Interface]
C[Strategy A]
D[Strategy B]
E[Strategy C]
A --> B
B --> C
B --> D
B --> E
Key Components
Strategy
Common algorithm interface.
Concrete Strategy
Actual implementation.
Context
Uses selected strategy.
UML Diagram
classDiagram
class Strategy {
+execute()
}
class CreditCardStrategy
class PayPalStrategy
class UpiStrategy
class PaymentContext
Strategy <|.. CreditCardStrategy
Strategy <|.. PayPalStrategy
Strategy <|.. UpiStrategy
PaymentContext --> Strategy
Payment Processing Example
Supported methods:
Credit Card
PayPal
UPI
All use different algorithms.
Step 1: Strategy Interface
public interface PaymentStrategy {
void pay(double amount);
}
Step 2: Credit Card Strategy
public class CreditCardStrategy
implements PaymentStrategy {
@Override
public void pay(
double amount) {
System.out.println(
"Paid using Credit Card: "
+ amount);
}
}
Step 3: PayPal Strategy
public class PayPalStrategy
implements PaymentStrategy {
@Override
public void pay(
double amount) {
System.out.println(
"Paid using PayPal: "
+ amount);
}
}
Step 4: UPI Strategy
public class UpiStrategy
implements PaymentStrategy {
@Override
public void pay(
double amount) {
System.out.println(
"Paid using UPI: "
+ amount);
}
}
Step 5: Context
public class PaymentContext {
private PaymentStrategy strategy;
public PaymentContext(
PaymentStrategy strategy) {
this.strategy = strategy;
}
public void processPayment(
double amount) {
strategy.pay(amount);
}
}
Step 6: Client
public class StrategyDemo {
public static void main(
String[] args) {
PaymentContext context =
new PaymentContext(
new CreditCardStrategy());
context.processPayment(5000);
context =
new PaymentContext(
new PayPalStrategy());
context.processPayment(7000);
}
}
Output
Paid using Credit Card: 5000
Paid using PayPal: 7000
Execution Flow
sequenceDiagram
Client->>Context: processPayment()
Context->>Strategy: pay()
Strategy-->>Client: Success
Discount Calculation Example
Strategies:
Regular Customer
Premium Customer
Gold Customer
Discount Architecture
flowchart LR
A[Customer]
B[Discount Strategy]
C[Regular]
D[Premium]
E[Gold]
A --> B
B --> C
B --> D
B --> E
Strategy Interface
public interface DiscountStrategy {
double calculate(
double amount);
}
Premium Strategy
public class PremiumDiscount
implements DiscountStrategy {
@Override
public double calculate(
double amount) {
return amount * 0.15;
}
}
Banking Example
Loan Interest Calculation.
Strategies:
Home Loan
Car Loan
Personal Loan
Different formulas.
Same interface.
Banking Workflow
flowchart LR
A[Loan Service]
B[Interest Strategy]
C[Home Loan]
D[Car Loan]
E[Personal Loan]
A --> B
B --> C
B --> D
B --> E
Insurance Example
Premium Calculation.
Strategies:
Health Insurance
Vehicle Insurance
Life Insurance
Different algorithms.
Insurance Flow
flowchart LR
A[Policy Service]
B[Premium Strategy]
C[Health]
D[Vehicle]
E[Life]
A --> B
B --> C
B --> D
B --> E
E-Commerce Example
Shipping Cost Calculation.
Strategies:
Standard Shipping
Express Shipping
International Shipping
Shipping Workflow
flowchart LR
A[Order]
B[Shipping Strategy]
C[Standard]
D[Express]
E[International]
A --> B
B --> C
B --> D
B --> E
Spring Security Example
Authentication Strategies:
Form Login
OAuth2
JWT
LDAP
Different authentication mechanisms.
Same contract.
Security Flow
flowchart LR
A[Authentication Request]
B[Authentication Strategy]
C[JWT]
D[OAuth]
E[LDAP]
A --> B
B --> C
B --> D
B --> E
Spring Framework Examples
Common Strategy Pattern usages:
Comparator
AuthenticationProvider
PasswordEncoder
Bean Validation
TaskExecutor
Comparator Example
Collections.sort(
employees,
comparator);
Different sorting strategies.
Java Comparator Workflow
flowchart LR
A[Collection]
B[Comparator Strategy]
C[Name Sort]
D[Salary Sort]
E[Date Sort]
A --> B
B --> C
B --> D
B --> E
Microservices Example
Notification Service.
Strategies:
Email
SMS
Push Notification
WhatsApp
Notification Flow
flowchart LR
A[Notification Request]
B[Notification Strategy]
C[Email]
D[SMS]
E[Push]
A --> B
B --> C
B --> D
B --> E
Real Enterprise Examples
Banking
Interest Calculation
Payment Processing
Fraud Detection
Insurance
Premium Calculation
Risk Assessment
Retail
Discount Calculation
Shipping Selection
Security
Authentication
Authorization
Benefits
✅ Eliminates Large If-Else Blocks
✅ Runtime Algorithm Selection
✅ Easy To Extend
✅ Open Closed Principle
✅ Cleaner Code
✅ Better Testing
Limitations
❌ More Classes
❌ Additional Complexity
❌ Overkill For Simple Logic
When To Use
Use Strategy Pattern when:
- Multiple algorithms exist
- Algorithm changes at runtime
- Large conditional logic exists
- Business rules vary frequently
When Not To Use
Avoid when:
- Only one algorithm exists
- Logic is simple
- No runtime selection is required
Strategy vs State
| Feature | Strategy | State |
|---|---|---|
| Purpose | Algorithm Selection | State Transition |
| Chosen By | Client | State Change |
| Focus | Behavior | Lifecycle |
Strategy vs Template Method
| Feature | Strategy | Template Method |
|---|---|---|
| Uses Composition | Yes | No |
| Uses Inheritance | No | Yes |
| Runtime Change | Yes | No |
Real Enterprise Architecture
flowchart LR
A[Application]
B[Context]
C[Strategy]
D[Algorithm]
A --> B
B --> C
C --> D
Interview Questions
What is Strategy Pattern?
A behavioral pattern that encapsulates interchangeable algorithms.
Main Components?
Context
Strategy
Concrete Strategy
Real Java Example?
Comparator
Spring Example?
AuthenticationProvider
PasswordEncoder
Main Benefit?
Runtime algorithm selection without modifying existing code.
Difference Between State and Strategy?
State manages lifecycle transitions.
Strategy manages interchangeable algorithms.
Key Takeaways
- Strategy is a Behavioral Design Pattern.
- Encapsulates interchangeable algorithms.
- Eliminates complex conditional logic.
- Supports runtime behavior changes.
- Common in Spring Security, Comparator, Payment Processing, and Discount Engines.
- Follows Open Closed Principle.
- One of the most frequently used enterprise design patterns.