SOLID & Design Patterns Interview Question #26
What is the Adapter Pattern?
Structural, Creational & Behavioral Patterns Junior Beginner
Quick Interview Answer
The Adapter Pattern converts the interface of an existing class into an interface that a client expects. It is useful when an application must integrate a legacy component, third-party library, or external service whose API does not match the application's abstraction.
Detailed Explanation
The Adapter Pattern converts the interface of an existing class into an interface that a client expects. It is useful when an application must integrate a legacy component, third-party library, or external service whose API does not match the application's abstraction.
The adapter contains the translation logic so the rest of the application does not depend directly on the incompatible API. This reduces coupling to external implementation details.
Code Example
public interface IPaymentGateway
{
Task PayAsync(decimal amount);
}
public class LegacyGatewayAdapter : IPaymentGateway
{
private readonly LegacyGateway _legacy;
public LegacyGatewayAdapter(LegacyGateway legacy)
=> _legacy = legacy;
public Task PayAsync(decimal amount)
{
_legacy.MakePayment((double)amount);
return Task.CompletedTask;
}
}