Tuesday, October 9, 2012

Easy explanation for Strategy design pattern using simple arithmetic calcuation

Strategy Design Pattern:

Detail :
http://en.wikipedia.org/wiki/Strategy_pattern


Use strategy when you need to define a family of algorithms, encapsulate each one, and make them
interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Strategy pattern are algorithms inside a class which can be interchanged depending on the class used.
This pattern is useful when you want to decide on run time which algorithm to be used.

Calculation.java

public interface Calculation {
int execute(int a, int b);
}

AddCalc.java
public class AddCalc implements Calculation{
@Override
public int execute(int a, int b) {
return a+b;
}
}

SubCalc.java
public class SubCalc implements Calculation{
@Override
public int execute(int a, int b) {
return a-b;
}
}


MultiCalc.java
public class MultiCalc implements Calculation{
@Override
public int execute(int a, int b) {
return a*b;
}
}

DivideCalc.java
public class DivideCalc implements Calculation{
@Override
public int execute(int a, int b) {
if(b==0) {return 0;}
return a/b;
}
}

MainStrategy.java
public class MainStrategy {
private Calculation calculation;
public MainStrategy(Calculation calculation){
this.calculation = calculation;
}

public int cal(int a,int b){
return calculation.execute(a, b);
}
}

Test.java
public int calculation(int first,int second,String operation){
MainStrategy mainStrategy = null;
if(operation.equals("add")){mainStrategy = new MainStrategy(new AddCalc());}
if(operation.equals("sub")){mainStrategy = new MainStrategy(new SubCalc());}
if(operation.equals("multi")){mainStrategy = new MainStrategy(new MultiCalc());}
if(operation.equals("div")){mainStrategy = new MainStrategy(new DivideCalc());}
return mainStrategy.cal(first, second);
}

0 comments:

Post a Comment