terminal

codeando_simple

terminal

menu

terminal

search_module

guest@codeandosimple: ~/system/search $ grep -r "" .

Press [ENTER] to execute search

Status

Engine: Ready

Database: Online

Index: V2.1.0_LATEST

bash -- cat strategy.md
guest@codeandosimple: ~/blog/design-patterns $ cat strategy.md

Strategy Pattern_

// "Don't forget that every book, every class, every challenge is a door to knowledge and understanding" - José Luis Sampedro

# Purpose

The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from clients that use it.

# Problem

  • Rigid Coupling: Mixing business logic with multiple algorithm implementations.

  • Statism: Inability to cleanly change runtime behavior.

# Solution

Encapsulate each algorithm in its own class (concrete strategy) and delegate its execution from the main class (context).

# Structure

Strategy UML Structure

# Participants

  • Context: Maintains a reference to the chosen strategy.
  • Strategy (Interface): Common interface for all algorithms.
  • ConcreteStrategy: Specific implementation of the algorithm.

# When to Use It

When you have multiple ways to perform a task and want to be able to dynamically swap them without filling the code with if/else statements.

# Advantages

  • verified

    Flexibility: Hot algorithm swapping.

  • verified

    Isolation: Complex algorithm logic does not pollute the Context class.

# Disadvantages

  • warning

    Communication Cost: Overhead when passing data between Context and Strategy.

  • warning

    Visibility: Clients must know what strategies exist to choose them.

# Example: Navigation System

Route calculation: Fastest, Shortest or Scenic. Each is a distinct strategy selected by the user.

Strategy Routes Example

# Java Code

interface RouteStrategy { void build(String a, String b); }

class FastestRoute implements RouteStrategy {
    public void build(String a, String b) { 
        System.out.println("Fastest route");
    }
}

class NavigationSystem {
    private RouteStrategy s;
    public void setStrategy(RouteStrategy s) { this.s = s; }
    public void navigate(String a, String b) { s.build(a, b); }
}

# Mapping Participants

  • RouteStrategy: Strategy Interface.
  • FastestRoute/ScenicRoute: ConcreteStrategies.
  • NavigationSystem: Context.

# Conclusions

Turns algorithms into modular, isolated, and easy-to-test building blocks.

# Related Patterns

Flyweight

Concrete strategies can be shared if they maintain no state.

State

Both use delegation, but Strategy is a specific choice made by the client.