Strategy Pattern
Strategy Pattern
In Strategy pattern, a class behavior or its algorithm can be changed at run time.
This type of design pattern comes under behavior pattern.
Implementation
We are going to create a Strategy interface defining an action and concrete strategy
classes implementing the Strategy interface. Context is a class which uses a
Strategy.
StrategyPatternDemo, our demo class, will use Context and strategy objects to
demonstrate change in Context behaviour based on strategy it deploys or uses.
Step 1
Create an interface.
Strategy.java
Step 2
Create concrete classes implementing the same interface.
OperationAdd.java
OperationSubstract.java
OperationMultiply.java
Step 3
Create Context Class.
Context.java
https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm 2/4
15/01/24, 11:44 Design Patterns - Strategy Pattern
Step 4
Use the Context to see change in behaviour when it changes its Strategy.
StrategyPatternDemo.java
Step 5
Verify the output.
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm 3/4
15/01/24, 11:44 Design Patterns - Strategy Pattern
https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm 4/4