DEV Community

Coder
Coder

Posted on • Originally published at itscoderslife.wordpress.com on

Adapter Design pattern [structural]

Motivation : When we need to adapt a framework but we cannot or do not want to modify its interface, yet we want to use it. The aim of the Adapter is to take the incompatible interface and adapt it to the one we need.

  • The Adapter should be used to make things work after they are designed.
  • Adapter is a right fit only when functionality is available but not in right interface.
  • Choose the adapter if you cannot change the source code of the incompatible type.
  • The Adapter is what actually adapts the incompatible interface to the one we require.
  • Don’t use an Adapter if you can modify the implementation.
  • You can also wrap the Adapter object in a dedicated Adapter class which exposes the API we need.

The Adapter pattern converts an existinginterface to another interface, which is required to make it compatible with the rest of the software system.

This pattern is useful when we need to integrate a component that provides similar functionality to other components in the system, but comes with an incompatible interface.

Example: What do we do when we have a HDMI port on our laptop and we need to connect it to a monitor with VGA? We use an adapter or a converter.

Let’s say you need to build an Photo sharing app which edits a photo and shares it on all social media – but interface for each one is different with various parameters. Facebook has its own parameter list, Twitter has different set, Tumblr has a different set. So we write a common (adapter) interface instead of using different interface for each of them. This keeps your app code clean and readable.

Summary : The Adapter pattern converts an incompatible interface into one that we need. The adapter can save us from a lot of refactoring work when integrating incompatible interfaces. By using the Adapter, we do not have to refactor our code to use the adaptee’s (framework’s) incompatible interface.

A common mistake we do is trying to adapt a component which does not provide the required functionality.

Top comments (0)