Tuesday, October 9, 2012

Command Design Pattern using simple example

Command Design Pattern:

Detail : http://en.wikipedia.org/wiki/Command_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;
}
}


Test.java
Map commands = new HashMap();
public Test(){
        commands.put("add", new AddCalc());
        commands.put("sub", new SubCalc());
        commands.put("multi", new MultiCalc());
        commands.put("div", new DivideCalc());
}

public int calc(int first,int second,String operation){
  Calcuation cal = commands.get(operation);
 return cal.execute(first,second);
}

0 comments:

Post a Comment