Friday, December 19, 2014

Adapter Design Pattern - Simple tutorial with an example in Java

Adapter Design Pattern belongs to the Structural Design Patterns group. You can use this pattern when you need to plug your existing code base to another code base which is not fully compatible with your existing code base. In such cases this pattern guarants the minimal change to your existing code.
Below I am showing you a very simple example which illustrates the use of this pattern. But note that in real world there are more complex situations where this pattern is used.

Assume that you have StudentData class which contains a list of ages of students.
public clas StudentData {
  private List<integer> ages;
}

Now think that for some reason you need to use a third party library which do some complex calculation using ages of students. This is that third party class.
public class ComplexCalculator {
  public int doComplexCalculation(String csv) {
    int result = 0;
    String[] ages = csv.split(",");
    //do complex calculation using ages
    //result = .....
    return result;
  }
}

Look, unfortunately the input type accepted by above method is csv. If you need to use this method you need to convert the list of ages in to a csv string. What do you do now? Change your StudentData class to include the csv generation logic. No. There is a cleaner way. Just create an adapter class(ComplexCalculatorAdapter) and let it do that dirty mediation job for you.
public class ComplexCalculatorAdapter {
  public int callComplexCalculator(List<integer> ages) {

    String csv = null;
    //Logic to create csv string from list
    //String csv = .......
    return new ComplexCalculator().doComplexCalculation(csv);
  }
}
Now in your StudentData class you can call this adapter method as below.
int complexResult = new ComplexCalculatorAdapter().callComplexCalculator(ages);

That is all.
Note that by using Adapter Design Pattern you were able to accomplish the above task with minimal modifications to the existing code.

No comments:

Post a Comment