Strategy pattern
The strategy pattern allows to select an algorithm at runtime.
This patter is used when the multiple classes differ only in their behaviors or you need different variations of an algorithm.
advantages
- Lets the algorithm vary independently from clients that use it.
- Allows you to easily extend and incorporate new behavior without modifying existing code.
strategy vs command
The strategy object defines how something should be done, and plugs into a larger object or method to provide a specific algorithm.
The command object is defined by what needs to be done. For example, it can take an operation and its arguments and wrap them up in an object to be logged, held for undo, etc.
example
// interface for strategy
interface Strategy {
float calc(float a, float b);
}
// concrete implementation of strategy
public class AddStrategy implements Strategy{
@Override
public float calc(float a, float b) {
return a+b;
}
}
// another concrete implementation of strategy
public class MulStrategy implements Strategy{
@Override
public float calc(float a, float b) {
return a*b;
}
}
// context, where strategy is used
public class Context {
private Strategy strategy;
public Context(Strategy strategy){
this.strategy = strategy;
}
public float performOperation(float a, float b){
return strategy.calculation(a, b);
}
}
public class DemoClient{
void task(float a, float b){
// ...
setSomeResult(
new Context(isMul ? new MulStrategy() : new AddStrategy()
);
// ...
}
}