Adapters are helpful if you want to use a class that doesn’t have quite the exact methods you need, and you can’t change the original class. The adapter can take the methods you can access in the original class, extracts data from them and adapt them to prepare the methods you need.

This pattern does exactly what its name indicates. It acts as an adapter between your application code and some 3rd party code you want to use. The 3rd party code can be some API or from some other source on which you have no control over. So when the code changes there on the 3rd party side, you may not like to change your application code, instead you can change the intermediate adapter class code to adapt to your particular need. Also in the situation where the 3rd party code provides some functionality you need but not in the exact way you require, you can use the adapter pattern to close the gap. Consider the below scenario.

Example:

Suppose the API of a Restaurant service provides two functions. One for getting all vegetarian dishes say get_veg_items() and another for getting the price of a dish if you know its item ID say, get_item_price(). But in your application you need data about the Veg. Items along with their prices. As the API doesn’t provide such method, you have to create it. This is where the adapter pattern comes to play. You create an intermediate class which takes input from the API, process it and gives the data your application requires. In this way if for some reason the API methods change in the future you can just change the adapter class to suit your needs without touching your application code.

Code:

The Adapter Class

The Menu Card Class:

Using the Classes:

You can notice that the operations in the intermediate adapter class can also be done in the MenuCard class, but if we do so and suppose in future the ResturantAPI changes its methods like adds a new one or removes an old one we have to change our client MenuCard class accordingly. This will not be a good design practice as it will increasing the coupling and will require heavy re-factoring. So this is a small example of a scenario where the Adapter pattern can come handy.