Strategy Pattern
What’s the Strategy Pattern ?
In the Wiki:
- defines a family of algorithms,
- encapsulates each algorithm
- makes the algorithms interchangeable within that family.
Motivation:
There are common situation when classes differ only in their behavior.For this case is good to isolate the algorithms in separate classes in order to have the ability to select different algorithm at runtime.
Intent
Difine a famliy of algorithms,ecapsulate each one, and make them interchangeable strategy lets the algorithm vary independently from clients that use it.
Example
Strategy -define an interface common to all supported algorithms.Context uses this interface to call algorithm defined by a StrategyPatternDemo.
Context
- contains a reference to a strategy object.
- may define an interface that lets strategy accessing its data.
Step 1
Strategy.java1
2
3public interface Strategy {
public int doOperation(int num1, int num2);
}
Step 2
OperationAdd.java1
2
3
4
5
6public class OperationAdd implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
OperationSubstract.java1
2
3
4
5
6public class OperationSubstract implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}
OperationMultiply.java1
2
3
4
5
6public class OperationMultiply implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 * num2;
}
}
Step 3
Context.java1
2
3
4
5
6
7
8
9
10
11public 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
StrategyPatternDemo.java
1 | public class StrategyPatternDemo { |
Referance
- https://en.wikipedia.org/wiki/Strategy_pattern
- http://www.tutorialspoint.com/design_pattern/strategy_pattern.htm
- http://www.oodesign.com/strategy-pattern.html