π§ Strategy Design Pattern in Java
The Strategy Design Pattern lets you define a family of algorithms, encapsulate each one, and make them interchangeable at runtime.
It's part of the behavioral design patterns category and is widely used in real-world applications.
π― Real-Life Analogy
π§ Think of a Google Maps app.
When you want directions, you can choose your route:
- πΆ Walk
- π Drive
- π΄ Cycle
The app uses a different strategy (algorithm) based on what you choose β but the interface remains the same: "Give me directions."
π§ When to Use Strategy Pattern?
- When you have multiple algorithms or behaviors for the same task.
- When you want to change behavior at runtime.
- To avoid massive
if-else
orswitch
logic blocks.
π₯ Example β Payment Strategies
Letβs say youβre building an e-commerce app that supports:
- π³ Credit Card
- π§Ύ UPI
- π¦ Net Banking
πΈ Step 1: Define a Strategy Interface
interface PaymentStrategy {
void pay(int amount);
}
πΈ Step 2: Implement Concrete Strategies
class CreditCardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid βΉ" + amount + " using Credit Card");
}
}
class UpiPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid βΉ" + amount + " using UPI");
}
}
class NetBankingPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid βΉ" + amount + " using Net Banking");
}
}
πΈ Step 3: Context Class (uses a strategy)
class PaymentContext {
private PaymentStrategy strategy;
public void setPaymentStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
public void payAmount(int amount) {
if (strategy == null) {
System.out.println("Please select a payment method.");
return;
}
strategy.pay(amount);
}
}
πΈ Step 4: Main Class to Test
public class PaymentApp {
public static void main(String[] args) {
PaymentContext context = new PaymentContext();
// Using UPI
context.setPaymentStrategy(new UpiPayment());
context.payAmount(500);
// Using Credit Card
context.setPaymentStrategy(new CreditCardPayment());
context.payAmount(1200);
// Using Net Banking
context.setPaymentStrategy(new NetBankingPayment());
context.payAmount(800);
}
}
β Output
Paid βΉ500 using UPI
Paid βΉ1200 using Credit Card
Paid βΉ800 using Net Banking
π§ Why Strategy Pattern?
| Feature | Benefit | | ------------- | -------------------------------------------------- | | Encapsulation | Each strategy is isolated | | Extensibility | Add new strategies without modifying existing code | | Reusability | Reuse strategies across contexts | | OCP Compliant | Open for extension, closed for modification |
π« Without Strategy: Massive If-Else Block β
public class PaymentService {
public void pay(String type, int amount) {
if (type.equals("UPI")) {
// UPI logic
} else if (type.equals("CREDIT")) {
// Credit card logic
} else if (type.equals("BANK")) {
// Net banking logic
}
// More logic = more pain
}
}
π This becomes hard to maintain and violates SRP and OCP.
π Bonus Example β Sorting Strategies
You can apply the Strategy pattern to choose different sorting algorithms dynamically.
interface SortStrategy {
void sort(int[] arr);
}
class BubbleSort implements SortStrategy {
public void sort(int[] arr) {
System.out.println("Sorting using Bubble Sort...");
// logic here
}
}
class QuickSort implements SortStrategy {
public void sort(int[] arr) {
System.out.println("Sorting using Quick Sort...");
// logic here
}
}
π§ Interview Q&A
Q: What type of pattern is Strategy? A: Behavioral pattern.
Q: Difference between Strategy and State Pattern? A:
- Strategy: Focuses on selecting algorithms dynamically.
- State: Focuses on objectβs behavior change based on internal state.
Q: Does Strategy follow SOLID principles? A: Yes β especially Open/Closed and Single Responsibility.
π Summary
- β Strategy Pattern allows dynamic switching between different algorithms.
- π§© Promotes loose coupling and clean design.
- π« Avoids hardcoding and conditional chaos.
- π οΈ Easy to maintain, extend, and test.