This pattern is commonly used in applications that have many functions or operations but all of them serve a specific entity.

For example, when you open your computer’s calculator, you will find many modes(Standard, Scientific, ..etc), Standard mode contains basic operations to solve any simple equation or calculation, Scientific mode contains the previous features and other advanced operations.

We can think that the basic operations in the Standard mode have been adapted with the new advanced operations to form the Scientific mode.

This is the idea of the Adapter pattern, we have 2 or more different classes and we want to make them compatible with each other.

The scenario is the following:-

[1] We have a basic standard calculator that contains basic 2 operation, add and subtract

[2] We want to create a calculator that contains the standard operation and other 2 advanced operations which are product and division

The standard calculator is inbuilt contain add and subtract operations

public interface Operations { public double calculate(double x, double y, char operation); }

The scientific calculator will have division and product operations

public interface AdvancedOperations { public double product(double x, double y); public double divide(double x, double y); }

Now, we will implement the scientific calculator class..

public static class Scientific implements AdvancedOperations { @Override public double product(double x, double y) { return x * y; } @Override public double divide(double x, double y) { return x / y; } }

The next step is to create an adapter, the adapter will use an object of scientific class and implement the standard calculator interface..

public static class CalculatorAdapter implements Operations { Scientific scientificMode; public CalculatorAdapter(String mode) { if (mode.equals("Scientific")) { this.scientificMode = new Scientific(); } } @Override public double calculate(double x, double y, char operation) { if (operation == '*') { System.out.println("Scientific"); return this.scientificMode.product(x, y); } else if(operation == '/') { System.out.println("Scientific"); return this.scientificMode.divide(x, y); } if (operation == '+') { System.out.println("Standard"); return x + y; //Standard inbuilt } else if (operation == '-') { System.out.println("Standard"); return x - y; // Standard inbuilt } return 0.0; } }

Finally, this is our new calculator that supports old and new operations.

public static class Calculator implements Operations { CalculatorAdapter calculatorAdapter; @Override public double calculate(double x, double y, char operation) { this.calculatorAdapter = new CalculatorAdapter("Scientific"); return this.calculatorAdapter.calculate(x, y, operation); } }

You can see the full implementation Here

References:

[1] GoF Book

[2] http://en.wikipedia.org/wiki/Adapter_pattern

## 2 thoughts on “Adapter Pattern”