Strategy Pattern
# Strategy Pattern
In the Strategy Pattern, a class's behavior or its algorithm can be changed at runtime. This type of design pattern falls under the behavioral pattern category.
The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. By using the Strategy Pattern, you can select different algorithms at runtime as needed without modifying the client code.
In the Strategy Pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object. The strategy object changes the executing algorithm of the context object.
## Introduction
### Intent
Define a family of algorithms, encapsulate each one, and make them interchangeable.
### Problem Solved
* Solves the complexity and maintenance issues caused by using conditional statements (like if...else) when multiple similar algorithms exist.
### Use Cases
* When a system has many classes that differ only in their behavior.
### Implementation Approach
* **Define the Strategy Interface**: All strategy classes will implement this common interface.
* **Create Concrete Strategy Classes**: Each strategy class encapsulates a specific algorithm or behavior.
* **Context Class**: Holds a reference to a strategy object and delegates the execution to that strategy.
### Key Code
* **Strategy Interface**: Specifies the method(s) that all strategy classes must implement.
* **Concrete Strategy Class**: Implements the strategy interface, containing the concrete algorithm implementation.
### Application Examples
1. **The "Bag of Tricks"**: Each "bag" represents a strategy, containing different tactics.
2. **Travel Mode Selection**: Riding a bicycle, taking a car, etc. Each mode is an interchangeable strategy.
3. **Java AWT's LayoutManager**: Different layout managers implement the same interface but provide different layout algorithms.
### Advantages
1. **Freedom to Switch Algorithms**: Algorithms can be switched at runtime as needed.
2. **Avoids Multiple Conditional Checks**: Eliminates complex conditional statements.
3. **Good Extensibility**: Adding a new algorithm only requires adding a new strategy class, without modifying existing code.
### Disadvantages
1. **Increased Number of Strategy Classes**: Each new algorithm requires a new strategy class.
2. **All Strategy Classes Must Be Exposed**: Strategy classes need to be public so they can be selected and used.
### Usage Recommendations
* Use the Strategy Pattern when a system has multiple algorithms or behaviors that are interchangeable.
* The Strategy Pattern is a suitable choice when a system needs to dynamically select an algorithm.
### Considerations
* If the number of strategy classes in the system becomes too large, consider using other patterns or design techniques to address class proliferation.
### Structure
**The Strategy Pattern includes the following core roles:**
* **Context**: Maintains a reference to a strategy object and is responsible for delegating the client request to the strategy object for execution. The context class can obtain the concrete strategy object through dependency injection, a simple factory, etc.
* **Abstract Strategy**: Defines the common interface or abstract class for strategy objects, specifying the methods that concrete strategy classes must implement.
* **Concrete Strategy**: Implements the interface or abstract class defined by the abstract strategy, containing the concrete algorithm implementation.
The Strategy Pattern decouples the algorithm from the code that uses it, providing a way to dynamically select different algorithms. The client code does not need to know the details of the concrete algorithm; instead, it uses the selected strategy by calling the context class.
## Implementation
We will create a _Strategy_ interface and concrete strategy classes that implement the _Strategy_ interface. The _Context_ is a class that uses a certain strategy.
_StrategyPatternDemo_, our demo class uses _Context_ and strategy objects to demonstrate the change in Context's behavior when its strategy changes.

### Step 1
Create an interface.
## Strategy.java
public interface Strategy{public int doOperation(int num1, int num2); }
### Step 2
Create concrete classes implementing the interface.
## OperationAdd.java
public class OperationAdd implements Strategy{ @Override public int doOperation(int num1, int num2){return num1 + num2; }}
## OperationSubtract.java
public class OperationSubtract implements Strategy{ @Override public int doOperation(int num1, int num2){return num1 - num2; }}
## OperationMultiply.java
public class OperationMultiply implements Strategy{ @Override public int doOperation(int num1, int num2){return num1 * num2; }}
### Step 3
Create the _Context_ class.
## Context.java
public class Context{private Strategy strategy; public Context(Strategy strategy){this.strategy = strategy; }public int executeStrategy(int num1, int num2){return strategy.doOperation(num1, num2); }}
### Step 4
Use the _Context_ to see change in behaviour when it changes its _Strategy_.
## StrategyPatternDemo.java
public class StrategyPatternDemo{public static void main(String[]args){Context context = new Context(new OperationAdd()); System.out.println("10 + 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationSubtract()); System.out.println("10 - 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationMultiply()); System.out.println("10 * 5 = " + context.executeStrategy(10, 5)); }}
### Step 5
Verify the output.
10 + 5 = 1510 - 5 = 510 * 5 = 50
YouTip