Strategy Design Pattern in Java with Examples | Beginner to Advanced Guide

Reading Time: 12–15 minutes

The Strategy Design Pattern is a behavioral design pattern that allows you to define multiple ways of performing a task and choose one at runtime. Instead of hardcoding logic using large if-else or switch conditions, each behavior is placed inside a separate class.

This makes the application flexible, easy to extend, and simple to maintain. Strategy pattern is commonly used when an application needs different variations of the same functionality.

This guide explains Strategy pattern from beginner to advanced level with simple explanations, step-by-step implementation, and real-world examples.

What is Strategy Design Pattern

The Strategy pattern defines a family of algorithms, encapsulates each algorithm into separate classes, and allows switching between them at runtime.

Simple definition:

Strategy pattern allows changing behavior dynamically without modifying existing code.

Each behavior is implemented separately and selected when needed.

Why Do We Need Strategy Pattern

Let us understand the problem first.

Problem Without Strategy Pattern

Suppose an e-commerce system provides different types of discounts.


package com.codekatha;

class DiscountService {

    public double calculateDiscount(String type, double price) {

        if (type.equals("FESTIVAL")) {
            return price * 0.20;
        }
        else if (type.equals("NEWUSER")) {
            return price * 0.10;
        }
        else if (type.equals("PREMIUM")) {
            return price * 0.30;
        }

        return 0;
    }
}

Problems in This Approach

Large conditional logic
Hard to add new discount types
Violates Open Closed Principle
Difficult to test and maintain
Code becomes complex over time

We need a design where discount logic is separated and easily replaceable.

Solution – Strategy Pattern

The Strategy pattern separates each discount calculation into different classes. The main class chooses which strategy to use at runtime.

This removes conditional logic and improves flexibility.

Key Idea Behind Strategy Pattern

Encapsulate behaviors into separate classes.
Make behaviors interchangeable.
Select behavior dynamically.

Structure of Strategy Pattern

Strategy Interface → Defines common behavior
Concrete Strategy → Implements specific behavior
Context Class → Uses selected strategy
Client → Chooses strategy

Step-by-Step Strategy Pattern Implementation

Step 1 – Create Strategy Interface

This interface defines the common discount behavior.


package com.codekatha;

interface DiscountStrategy {
    double applyDiscount(double price);
}

Step 2 – Create Concrete Strategy Classes

Each class implements a different discount algorithm.


package com.codekatha;

class FestivalDiscount implements DiscountStrategy {

    public double applyDiscount(double price) {
        return price * 0.20;
    }
}

class NewUserDiscount implements DiscountStrategy {

    public double applyDiscount(double price) {
        return price * 0.10;
    }
}

class PremiumUserDiscount implements DiscountStrategy {

    public double applyDiscount(double price) {
        return price * 0.30;
    }
}

Step 3 – Create Context Class

This class uses the selected strategy to perform the operation.


package com.codekatha;

class PriceCalculator {

    private DiscountStrategy discountStrategy;

    public PriceCalculator(DiscountStrategy discountStrategy) {
        this.discountStrategy = discountStrategy;
    }

    public double calculateFinalPrice(double price) {
        return price - discountStrategy.applyDiscount(price);
    }
}

Step 4 – Client Code

The client selects the required strategy at runtime.


package com.codekatha;

class StrategyDemo {

    public static void main(String[] args) {

        PriceCalculator calculator =
                new PriceCalculator(new FestivalDiscount());

        System.out.println(calculator.calculateFinalPrice(1000));

        calculator =
                new PriceCalculator(new PremiumUserDiscount());

        System.out.println(calculator.calculateFinalPrice(1000));
    }
}

What We Achieved Using Strategy Pattern

Removed complex conditional statements
Behavior can change dynamically
Loose coupling between components
Easy to add new discount logic

Real-Life Example of Strategy Pattern

Consider an online shopping platform.

Festival discount
New user discount
Premium member discount

The product price remains the same, but the discount strategy changes based on the user.

Strategy vs Factory Pattern

Factory pattern focuses on object creation.
Strategy pattern focuses on behavior selection.

Key Difference

Factory decides which object to create.
Strategy decides how a task is performed.

How Strategy Supports Open Closed Principle

New strategies can be added without modifying existing code.

For example, adding SeasonalDiscount only requires creating a new class implementing DiscountStrategy.

Advantages of Strategy Pattern

Removes large conditional logic
Improves flexibility
Supports runtime behavior change
Promotes clean and maintainable code
Easy to extend

Disadvantages of Strategy Pattern

More classes required
Client must understand different strategies
Slightly increased system complexity

When Should You Use Strategy Pattern

When multiple ways exist to perform a task
When behavior must change at runtime
When code contains many if-else conditions
When algorithms vary independently

Real-World Usage of Strategy Pattern

Discount calculation systems
Tax calculation logic
Sorting algorithm selection
Navigation route selection
Spring framework implementations

Common Interview Questions on Strategy Pattern

What problem does Strategy solve?
Difference between Strategy and Factory?
When should Strategy be used?
How does Strategy follow Open Closed Principle?

Simple Summary

Strategy pattern separates behaviors into different classes.
Behavior can be changed dynamically.
Improves flexibility and maintainability.
Removes complex conditional logic.

Conclusion

The Strategy Design Pattern helps design flexible systems by separating algorithms into independent classes. It simplifies maintenance, improves scalability, and allows dynamic behavior selection.

Understanding Strategy pattern is important for building clean and scalable enterprise applications.

Comments

Popular Posts on Code Katha

Java Interview Questions for 10 Years Experience

Sql Interview Questions for 10 Years Experience

Spring Boot Interview Questions for 10 Years Experience

Java interview questions - Must to know concepts

Visual Studio Code setup for Java and Spring with GitHub Copilot

Spring AI with Ollama

Data Structures & Algorithms Tutorial with Coding Interview Questions

Spring Data JPA

Topological Sort in Graph

Bit Manipulation and Bit Masking Concepts