Knowledge Guide
HomeOO & Low-Level DesignBehavioral

Strategy Pattern

The Strategy design pattern is a behavioral design pattern that allows you to change the behavior of an algorithm at runtime. Instead of explicitly implementing a single method, code receives run-time instructions describing which among a family of algorithms to use.

Consider a logistics firm that needs to determine the cost of shipping products. The shipping cost is determined by several elements, including the destination, weight, and delivery method (air, road, or sea). Putting all of these computations into one class would result in a complicated, difficult-to-maintain system, particularly if additional shipping options or price adjustments are made.

Strategy Pattern - Logistics Company Example
Strategy Pattern - Logistics Company Example

The shipping cost calculation strategies should be divided into distinct classes that each implement the same interface according to the strategy pattern. Next, without knowing which particular method is being used, the logistics system refers to this interface to determine the shipping cost. This method makes it simple to add new strategies without modifying the current code and enables dynamic changes to the shipping cost calculation strategy based on requirements.

Real-World Example

Consider organizing a trip. For every part of your trip, including accommodation, activities, and transportation, you have a number of options. Each choice of travel planning can be viewed as a strategy.

Strategy Pattern - Real-life Example
Strategy Pattern - Real-life Example

How the Strategy Pattern Connects with This

You select a plan for all aspects of travel planning based on your tastes, financial constraints, and the purpose of the trip. You choose algorithms (or strategies) at runtime depending on your present context (the vacation you're planning), just like in the Strategy pattern. It's simple to change strategies, like driving to flying, without changing the entire itinerary.

Structure of Strategy Pattern

  1. Context:
    • Maintains a reference to a Strategy object.
    • Can be configured with a ConcreteStrategy object.
    • May define an interface that lets Strategy access its data.
  2. Strategy Interface:
    • Declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy.
  3. Concrete Strategies:
    • Implements the algorithm using the Strategy interface.
    • Provides various alternatives for the behavior encapsulated in the Context.
Strategy Pattern - Class Diagram
Strategy Pattern - Class Diagram

The class diagram for the Strategy pattern typically shows the Context class linked to the Strategy interface, which is then implemented by multiple ConcreteStrategy classes. This design allows the Context to delegate some of its behaviors to the strategies defined by these ConcreteStrategy classes.

#1## Implementation of Strategy Pattern

Let's implement the Logistics Company Example in pseudocode:

// Strategy interfaces interface TransportationStrategy: method travelPlan() returns string interface AccommodationStrategy: method stayPlan() returns string interface ActivityStrategy: method activityPlan() returns string // Concrete Strategies class AirTravel implements TransportationStrategy: method travelPlan() returns string: return "Travel by air: Fast and convenient for long distances." class TrainTravel implements TransportationStrategy: method travelPlan() returns string: return "Travel by train: Enjoy scenic routes and comfortable travel." class RoadTravel implements TransportationStrategy: method travelPlan() returns string: return "Travel by road: Flexible and ideal for exploration." class HotelStay implements AccommodationStrategy: method stayPlan() returns string: return "Stay in a hotel: Enjoy comfort and luxury services." class HostelStay implements AccommodationStrategy: method stayPlan() returns string: return "Stay in a hostel: Budget-friendly and social environment." class VacationRentalStay implements AccommodationStrategy: method stayPlan() returns string: return "Stay in a vacation rental: Privacy and a homely feel." class AdventureSports implements ActivityStrategy: method activityPlan() returns string: return "Engage in adventure sports: Exciting and thrilling experiences." class CulturalTours implements ActivityStrategy: method activityPlan() returns string: return "Go on cultural tours: Explore local culture and historical sites." class RelaxationActivities implements ActivityStrategy: method activityPlan() returns string: return "Relax at beaches or spas: Leisure and tranquility." // Context Class: Travel Plan class TravelPlan: transportationStrategy: TransportationStrategy accommodationStrategy: AccommodationStrategy activityStrategy: ActivityStrategy method setTransportationStrategy(TransportationStrategy strategy): this.transportationStrategy = strategy method setAccommodationStrategy(AccommodationStrategy strategy): this.accommodationStrategy = strategy method setActivityStrategy(ActivityStrategy strategy): this.activityStrategy = strategy method generatePlan() returns string: return transportationStrategy.travelPlan() + "\n" + accommodationStrategy.stayPlan() + "\n" + activityStrategy.activityPlan() //Usage: travelPlan = new TravelPlan() // Setting different strategies travelPlan.setTransportationStrategy(new AirTravel()) travelPlan.setAccommodationStrategy(new HotelStay()) travelPlan.setActivityStrategy(new CulturalTours()) // Generate and print the travel plan print(travelPlan.generatePlan())

Implementations

java
// Strategy Interfaces
interface TransportationStrategy {
    String travelPlan();
}

interface AccommodationStrategy {
    String stayPlan();
}

interface ActivityStrategy {
    String activityPlan();
}

// Concrete Strategies
class AirTravel implements TransportationStrategy {
    public String travelPlan() {
        return "Travel by air: Fast and convenient for long distances.";
    }
}

class HotelStay implements AccommodationStrategy {
    public String stayPlan() {
        return "Stay in a hotel: Enjoy comfort and luxury services";
    }
}

class AdventureSports implements ActivityStrategy {
    public String activityPlan() {
        return "Engage in adventure sports: Exciting and thrilling experiences.";
    }
}

// Context Class: Travel Plan
class TravelPlan {
    private TransportationStrategy transportationStrategy;
    private AccommodationStrategy accommodationStrategy;
    private ActivityStrategy activityStrategy;

    public void setTransportationStrategy(TransportationStrategy strategy) {
        this.transportationStrategy = strategy;
    }

    public void setAccommodationStrategy(AccommodationStrategy strategy) {
        this.accommodationStrategy = strategy;
    }

    public void setActivityStrategy(ActivityStrategy strategy) {
        this.activityStrategy = strategy;
    }

    public String generatePlan() {
        StringBuilder plan = new StringBuilder();
        if (transportationStrategy != null) {
            plan.append(transportationStrategy.travelPlan()).append("\n");
        }
        if (accommodationStrategy != null) {
            plan.append(accommodationStrategy.stayPlan()).append("\n");
        }
        if (activityStrategy != null) {
            plan.append(activityStrategy.activityPlan()).append("\n");
        }
        return plan.toString();
    }
}

// Usage Example
public class Solution {
    public static void main(String[] args) {
        TravelPlan travelPlan = new TravelPlan();
        travelPlan.setTransportationStrategy(new AirTravel());
        travelPlan.setAccommodationStrategy(new HotelStay());
        travelPlan.setActivityStrategy(new AdventureSports());
        System.out.println(travelPlan.generatePlan());
    }
}

Applications of Strategy Pattern

Pros and Cons

ProsCons
Flexibility: Easily switch between different algorithms or strategies at runtime.Complexity: Can increase the complexity of the code with multiple strategy classes.
Scalability: Simplifies adding new strategies without modifying the existing code.Overhead: Additional overhead in terms of memory and runtime, especially with a large number of strategies.
Maintainability: Changes in algorithms or strategies don't affect the client code, improving maintainability.Understanding: Requires a good understanding of each strategy to use it effectively.
Decoupling: Separates the concerns by decoupling algorithm implementation from the business logic.Initial Setup: More upfront work is needed to define strategy interfaces and concrete classes.
Testability: Easier to unit test each strategy independently.Multiple Objects: May lead to an increased number of objects in the system.

The Strategy pattern is a versatile tool in the toolkit of a developer, providing flexibility and maintainability in cases where numerous solutions for one specific task exist. It is particularly effective in systems where runtime behavior changes are required. By understanding and using this pattern, software design can be significantly enhanced, leading to easier extensions and modifications in the future.

🤖 Don't fully get this? Learn it with Claude

Stuck on Strategy Pattern? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Strategy Pattern** (OO & Low-Level Design) and want to truly understand it. Explain Strategy Pattern from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Strategy Pattern** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Strategy Pattern** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Strategy Pattern** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes