Skip to main content

What is the main purpose of the Adapter pattern?

The main purpose of the Adapter pattern is to make incompatible interfaces compatible, that is, to let objects with different interfaces work together without changing their code.


1. The Core Idea

Sometimes you need to use a third-party or legacy class whose interface does not match what the rest of the system expects. The adapter acts as a layer (wrapper) that "translates" calls from one interface into another, ensuring compatibility.


2. When It Is Used

  • When you need to integrate legacy code with a new system.
  • When there is a library or external API whose interface cannot be changed.
  • When different components of a system must work through a single interface but are implemented differently.

3. Example (Java)

Suppose we have a modern interface:

java
interface MediaPlayer { void play(String file); }

and an old class:

java
class OldPlayer { void startPlayback(String filePath) { System.out.println("Playing " + filePath); } }

The adapter "translates" the interface:

java
class PlayerAdapter implements MediaPlayer { private OldPlayer oldPlayer = new OldPlayer(); public void play(String file) { oldPlayer.startPlayback(file); } }

Now the old OldPlayer can be used in the new system through the MediaPlayer interface.


4. Advantages

  • Allows you to reuse existing code without changing it.
  • Provides flexibility and compatibility between different systems.
  • Supports the open/closed principle (OCP): the adapter is added, it does not modify existing code.

5. Conclusion

Adapter solves the problem of integrating incompatible interfaces, turning them into a single interaction format without breaking encapsulation or requiring changes to the original classes.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.