DEV Community

Cover image for Adapter Design Pattern
Common Khadka
Common Khadka

Posted on

Adapter Design Pattern

  • Allows two completely incompatiable interface to work together.

  • Used when the client excepts a (target) interface

  • The adapter class allows the use of the available interface and the target interface.

  • Any class can work together as long as the adapter solves the issue that all classes must implement every method defined by the shared interface.

Image description

Video Source

The Adapter design pattern is used to allow incompatible interfaces to work together.
It acts as a bridge between two incompatible interfaces by converting the interface of a class into another interface that a client expects.

Here's a simple example in C# to illustrate the Adapter pattern:

Suppose you have an existing OldSystem class with a method Request, and you want to adapt it to work with a new system that expects a different interface, INewSystem.
The OldSystemAdapter class serves as the adapter to make the OldSystem compatible with the INewSystem interface.

using System;

// Existing system with an incompatible interface
public class OldSystem
{
    public void Request()
    {
        Console.WriteLine("OldSystem is handling the request.");
    }
}

// New system with a different interface
public interface INewSystem
{
    void NewRequest();
}

// Adapter class that adapts OldSystem to INewSystem
public class OldSystemAdapter : INewSystem
{
    private readonly OldSystem oldSystem;

    public OldSystemAdapter(OldSystem oldSystem)
    {
        this.oldSystem = oldSystem;
    }

    public void NewRequest()
    {
        // Call the existing OldSystem's method from the adapted interface
        oldSystem.Request();
    }
}

// Client code that expects INewSystem interface
public class Client
{
    public void UseSystem(INewSystem system)
    {
        system.NewRequest();
    }
}

class Program
{
    static void Main()
    {
        // Using the existing OldSystem with the help of the adapter
        OldSystem oldSystem = new OldSystem();
        INewSystem adapter = new OldSystemAdapter(oldSystem);

        // Client code works with the INewSystem interface
        Client client = new Client();
        client.UseSystem(adapter);
    }
}

Enter fullscreen mode Exit fullscreen mode

In this example:

OldSystem is the existing class with an incompatible interface.
INewSystem is the new interface expected by the client.
OldSystemAdapter is the adapter class that implements INewSystem by delegating calls to the existing OldSystem.

The client code (Client class) works with INewSystem and is unaware of the existence of OldSystem.
The adapter bridges the gap between the existing system and the client's expectations.

This is a simplified example, but it illustrates the basic structure of the Adapter pattern. In real-world scenarios, you might encounter more complex interfaces and interactions.

Top comments (0)