System Design ( Day - 52 )

Manoj KumarManoj Kumar
2 min read

Adapter Design Pattern

Definition
Adapter converts the interface of a class into another interface that client expects, adapter let’s classes work together that couldn’t otherwise because of incomplete interfaces.

📦 1. Real-World Example: XML → JSON Adapter

🎯 The Problem

Your client code expects to call:

IReports reports = …;
String json = reports.getJsonData();

But you only have an old XML provider:

class XmlDataProvider {
  String getXmlData() { /* … */ }
}

🔌 The Adapter

// Target interface your client uses:
public interface IReports {
  String getJsonData();
}

// Adaptee: legacy XML data source
class XmlDataProvider {
  String getXmlData() { /* read XML… */ }
}

// Adapter: “is-a” IReports, “has-a” XmlDataProvider
class XmlDataProviderAdapter implements IReports {
  private XmlDataProvider provider;

  public XmlDataProviderAdapter(XmlDataProvider provider) {
    this.provider = provider;
  }

  @Override
  public String getJsonData() {
    // 1️⃣ fetch XML
    String xml = provider.getXmlData();
    // 2️⃣ convert to JSON
    return XmlToJsonConverter.convert(xml);
  }
}

🔄 How It Flows

  1. Client holds an IReports reference.

  2. You inject an XmlDataProviderAdapter (wrapping the legacy XmlDataProvider).

  3. Client calls getJsonData().

  4. Adapter under the hood fetches XML and converts it to JSON.

📐 2. Standard UML Blueprint

       <<abstract>>           <<adaptee>>
      +-------------+        +-----------+
      |  ITarget    |<>─────▶| Adaptee   |
      | + request() |        | + specificRequest() |
      +-------------+        +-----------+
             ▲
             |
      +--------------+
      |   Adapter    |
      |− adaptee     |
      |+ request()   |
      +--------------+
             ▲
             |
         Client
        +-------+
        | calls |
        +-------+
  • ITarget defines the interface the Client expects.

  • Adaptee is the existing class with a mismatched API.

  • Adapter implements ITarget and delegates calls to Adaptee, translating as needed.


🌟 Why Use Adapter?

  • Reuses legacy code without modifying it

  • Decouples client from concrete implementations

  • Keeps your codebase clean, adhering to the Open/Closed Principle

Real world use case.

  1. Whenever we have to implement the 3rd party services to our applications then we can use this adapter design pattern to link our application with 3rd party service.

  2. Whenever we want to talk to our legacy code in our application then also we can use this adapter patter to talk from our latest code to the legacy code easily.

0
Subscribe to my newsletter

Read articles from Manoj Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Manoj Kumar
Manoj Kumar