In day-to-day design/development many places we need to use the patterns, but most of the times we just write the code without knowing the exact patterns.
Patterns can make the system robust and can re-use it.
I share my experience with the design patterns.
Startegy Pattern
In Strategy Pattern, the algorithms(behavior) can be selected at run time.
The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them. |
Example code:
Following program add/subtract/multiply/divide(s) the two numbers and this add/subtract/multiply/divide behavior(strategy) has been extracted out defined as a interface.
This strategy has been referenced in the context class and it can be changed dynamically using the constructor/setter method.
//StrategyPatternSample
class StrategySample {
public static void main(String[] args) {
Context context;
context = new Context(new StrategyAdd());
System.out.println(context.executeStrategy(12,3));
context = new Context(new StrategySubtract());
System.out.println(context.executeStrategy(12,3));
context = new Context(new StrategyMultiply());
System.out.println(context.executeStrategy(12,3));
context = new Context(new StrategyDivide());
System.out.println(context.executeStrategy(12,3));
}
}
// The strategy interface
interface IStrategy {
int run(int a, int b);
}
// Implements the algorithm using the strategy interface
class StrategyAdd implements IStrategy {
public int execute(int a, int b) {
System.out.println("add");
return a + b;
}
}
class StrategySubtract implements IStrategy {
public int execute(int a, int b) {
System.out.println("subtract");
return a - b;
}
}
class StrategyMultiply implements IStrategy {
public int execute(int a, int b) {
System.out.println("multiply");
return a * b;
}
}
class StrategyDivide implements IStrategy {
public int execute(int a, int b) {
System.out.println("divide");
return a / b;
}
// Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
class Context {
private IStrategy strategy;
// Constructor
public Context(IStrategy strategy) {
this.strategy = strategy;
}
public int executeStrategy(int a, int b) {
return strategy.execute(a, b);
}
//setter method for strategy
public void setStrategy(IStrategy strategy) {
this.strategy = strategy;
}
}