Course contentsShow
← Computer Science
Lesson 2274 of 2,87251. Design PatternsFree lesson

Adapter Pattern: Converting Interfaces

Learn how the Adapter pattern allows incompatible interfaces to work together by wrapping one interface to match another.

Adapter Pattern: Converting Interfaces

You'll learn how to make incompatible code components work together by wrapping one interface to match another's expectations.

The Problem: Incompatible Interfaces

Imagine you have two classes that should work together but can't because they speak different "languages"—their method names, parameters, or structure don't match. You can't always modify the original classes (they might be third-party libraries or legacy code). This is where the Adapter pattern saves the day.

How the Adapter Pattern Works

The Adapter pattern acts as a translator between two incompatible interfaces. You create an adapter class that wraps the incompatible object and exposes the interface your client code expects.

Real-world analogy: Think of a power plug adapter when traveling abroad. Your laptop charger (the client) expects a certain socket shape, but the wall outlet (the adaptee) has a different shape. The adapter converts one interface to match the other without changing either the charger or the wall.

The Structure

  1. Target Interface: What your client code expects
  2. Adaptee: The existing class with an incompatible interface
  3. Adapter: The wrapper that implements the target interface and delegates to the adaptee

The adapter receives calls through the target interface, translates them, and forwards them to the adaptee's methods. It may transform parameters, change method names, or even combine multiple calls.

When to Use It

  • Integrating third-party libraries with incompatible interfaces
  • Reusing legacy code in new systems
  • Working with classes you cannot modify
  • Making two existing classes collaborate without rewriting them

Key Takeaway: The Adapter pattern lets incompatible interfaces collaborate by providing a wrapper that translates one interface into another, enabling integration without modifying existing code.