Strategy Design Pattern

Loading...
By technoayan
Design-PatternStrategy
Strategy Design Pattern
0 min read
LLD
Design-Pattern
Strategy

Strategy Design Pattern

Master the Strategy Design Pattern in Java with simple explanations, real-world analogies, and working code examples. Learn how to write flexible and extensible code using behavior encapsulation.

🧠 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 or switch 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

β˜•JAVA
interface PaymentStrategy {
    void pay(int amount);
}

πŸ”Έ Step 2: Implement Concrete Strategies

β˜•JAVA
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)

β˜•JAVA
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

β˜•JAVA
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 ❌

β˜•JAVA
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.

β˜•JAVA
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.

Thanks for reading!

technoayan

Author & Tech Enthusiast

"Keep learning, keep growing, and keep sharing knowledge with the world."

Rate This Post

Share your thoughts and help others discover great content

Sign in to rate this post and share your feedback

Community Rating

No ratings yet. Be the first to rate this post!

Comments (0)

Leave a Comment

No comments yet. Be the first to share your thoughts!

TechnoBlogs

by Ayan Ahmad

Exploring the world of technology through insightful articles, tutorials, and personal experiences. Join me on this journey of continuous learning and innovation.

Stay Updated

Built With

React
Next.js
Tailwind
Firebase
Powered by Coffee

Every line of code written with love and caffeine β˜•

Β© 2025 TechnoBlogsβ€’Made withbyAyan Ahmad

Open source β€’ Privacy focused β€’ Built for developersβ€’Privacy Policyβ€’Terms of Service