Adapter design pattern

Adapter design pattern is probably one of the simplest, yet very useful design pattern. Let’s take and example, you have a device which runs on Direct Current (DC), but in your home you have supply of Alternate current (AC). What will you do? Go to an electronic shop and explain the problem, the guy in shop will give you an AC to DC ‘Adapter’. What it does is basically takes AC as input and provide DC as output for your device.

Similar problems are faced at times by developer, especially when they are using API from third party or legacy code. Say you are using a Tax class API (you do not have code) which takes integer to calculate tax in its getTax method, whereas your code stores the data in int. One way is to convert the format at every place in code where ever you are using getTax. A second and simple ‘Adapter’ way will be to create a TaxAdapter class which will have a getTax in it, which further calls getTax of Tax class. The only responsibility of TaxAdapter is to convert the data into a format which is expected by Tax class(double to int, AC to DC).

Leave a Reply