There are common situations when classes differ only in their behavior.
For this cases, it is a good idea to isolate the algorithms in separate
classes in order to have the ability to select different algorithms at
runtime.If you still not sure what the hell this pattern will do but like to deal with objects and like to see your code simple, cleaner and more maintainable, i am pretty sure you will become fan of it.Lets explore a very simple example of strategy pattern and feel its power :).
// The classes that implement a concrete strategy should implement this.
// The Context class uses this to call the concrete strategy.
interface Strategy {
int execute(int a,int b);
}
// Implements the algorithm using the strategy interface
class ConcreteStrategyAdd implements Strategy {
public int execute(int a, int b){
return a + b; // Do an addition with a and b
}
}
class ConcreteStrategySubtract implements Strategy {
public int execute(int a, int b) {
return a - b; // Do a subtraction with a and bclass
}
}
class ConcreteStrategyMultiply implements Strategy {
public int execute(int a, int b) {
return a * b; // Do a multiplication with a and b
}
}
/**
* Configured with a ConcreteStrategy object and maintains a
* reference to a Strategy object.
*/
class Context{
private Strategy strategy;
// Constructor
public Context(Strategy strategy){
this.strategy = strategy;
}
public int executeStrategy(int a, int b) {
return strategy.execute(a, b);
}
}
// Test application
class StrategyExample{
public static void main(String[]) {
Context context;
// Three contexts following different strategies
context = new Context(new ConcreteStrategyAdd());
int resultA = context.executeStrategy( 3,4);
context = new Context(new ConcreteStrategySubtract());
int resultB = context.executeStrategy(3,4);
context = new Context(new ConcreteStrategyMultiply());
int resultC = context.executeStrategy(3,4);
}
}
Simple and smart!!!!!!! isn't it?Enjoy happy coding :).

No comments:
Post a Comment