Strategy Pattern
In the Strategy Pattern, the behavior or algorithm of a class can be changed at runtime. This type of design pattern belongs to the behavioral patterns.
The Strategy Pattern defines a series of algorithms or strategies and encapsulates each algorithm in a separate class so that they can be interchanged. By using the Strategy Pattern, different algorithms can be selected at runtime as needed without modifying the client code.
In the Strategy Pattern, we create objects representing various strategies and a context object whose behavior changes as the strategy object changes. The strategy object changes the execution algorithm of the context object.
Introduction
Intent
Encapsulate each algorithm so that they can be used interchangeably.
Main problem solved
- Solves the complexity and difficult maintenance caused by using conditional statements (such as if...else) when multiple similar algorithms exist.
Use Cases
- When a system has many classes that differ only in their behavior.
Implementation
- Define the strategy interface: All strategy classes will implement this unified interface.
- Create concrete strategy classes: Each strategy class encapsulates a specific algorithm or behavior.
- Context Class: Contains a reference to a strategy object and invokes the strategy through that reference.
Key code
- Strategy Interface: Specifies the methods that all strategy classes must implement.
- Concrete strategy classes: Implements the strategy interface and contains specific algorithm implementations.
Application Example
- Brilliant strategies: Each bag represents a strategy containing different tactics.
- Travel mode selection: Riding a bicycle, taking a car, etc., each mode is a replaceable strategy.
- Java AWT's LayoutManager: Different layout managers implement the same interface but provide different layout algorithms.
Advantages
- Free algorithm switching: Algorithms can be switched at runtime as needed.
- Avoid multiple conditional judgments: Eliminates complex conditional statements.
- Good extensibility: Adding a new algorithm only requires adding a new strategy class, without modifying existing code.
Disadvantages
- Increased number of strategy classes: Each new algorithm requires an additional strategy class.
- All strategy classes need to be exposed: Strategy classes need to be exposed so that they can be selected and used.
Usage recommendation
- Use the Strategy Pattern when a system has multiple algorithms or behaviors that can be interchanged.
- When a system needs to dynamically select an algorithm, the Strategy Pattern is a suitable choice.
Notes
- If there are too many strategy classes in a system, consider using other patterns or design techniques to solve the class explosion problem.
structures
The Strategy Pattern contains the following core roles:
- Context: Maintains a reference to a strategy object and is responsible for delegating client requests to the concrete strategy object for execution. The context class can obtain the concrete strategy object through dependency injection, simple factory, etc.
- Abstract Strategy: Defines the common interface or abstract class of strategy objects, specifying the methods that concrete strategy classes must implement.
- Concrete Strategy: Implements the interface or abstract class defined by the abstract strategy and contains specific algorithm implementations.
The Strategy Pattern provides a way to dynamically select different algorithms by decoupling algorithms from the code that uses them. Client code does not need to know the specific algorithm details, but uses the selected strategy by calling the context class.
Create a class that implements
We will create concrete strategy classes of the interface that defines an Strategy interface as the bridge implementation and concrete classes that implement the Strategy activity.Context is a class that uses a certain strategy.
StrategyPatternDemo, and our demo class uses the Context and strategy objects to demonstrate the behavior changes of Context when the strategy it is configured with or uses changes.
Step 1
Create an interface.
Strategy.java
public
interface
Strategy
{
public
int
doOperation
(
int
num1
,
int
num2
)
;
}
Step 2
Create concrete classes that implement 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
creation 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 Context to see when it changes strategy Strategy the behavior changes.
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
Run the program, output result:
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50