DEV Community

Juarez Júnior
Juarez Júnior

Posted on

C# Design Pattern: Adapter

The Adapter pattern is useful when you need two classes with incompatible interfaces to work together. It creates a “bridge” between the classes, converting the interface of one class into another expected by the client. This is useful in situations such as integrating a new feature or library into an existing system where the interfaces are not compatible, or when you want to reuse an existing class without modifying it directly.

C# Code Example:

// Existing class (incompatible with client)
public class EuropeanSocket
{
    public void ConnectEuropeanPlug()
    {
        Console.WriteLine("European plug connected to European socket.");
    }
}

// Client's interface
public interface ISocket
{
    void Connect();
}

// Adapter that makes EuropeanSocket compatible with ISocket
public class SocketAdapter : ISocket
{
    private EuropeanSocket _europeanSocket;

    public SocketAdapter(EuropeanSocket europeanSocket)
    {
        _europeanSocket = europeanSocket;
    }

    public void Connect()
    {
        // Adapting the call
        _europeanSocket.ConnectEuropeanPlug();
    }
}

// Client using the ISocket interface
class Program
{
    static void Main(string[] args)
    {
        // Client needs a socket compatible with ISocket
        ISocket socket = new SocketAdapter(new EuropeanSocket());
        socket.Connect();  // Output: European plug connected to European socket.
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In this example, we have the EuropeanSocket class with a specific method that is incompatible with the ISocket interface that the client expects. The SocketAdapter is created to bridge the gap between the client and the EuropeanSocket, adapting the Connect() call to ConnectEuropeanPlug(). The main code shows how the client can use the adapter to work with the European socket without modifying it directly.

Conclusion:

The Adapter pattern is useful for integrating classes with incompatible interfaces, allowing them to work together without changes to their original implementations. It is ideal for scenarios where you want to reuse or integrate new functionalities into existing systems without breaking or rewriting the code that is already developed.

Source code: GitHub

Top comments (0)