Skip to content

Adapter

Context: Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

// Adaptee
public class Adaptee
{
public string SpecificRequest() => "Specific response";
}
// Target interface
public interface ITarget
{
string Request();
}
// Adapter
public class Adapter : ITarget
{
private readonly Adaptee _adaptee;
public Adapter(Adaptee adaptee) => _adaptee = adaptee;
public string Request() => _adaptee.SpecificRequest();
}
// Usage
Adaptee adaptee = new();
ITarget target = new Adapter(adaptee);
Console.WriteLine(target.Request());

Database providers: An application uses a common IDatabase interface. Adapters for MySQL, PostgreSQL, and SQL Server convert their native APIs to IDatabase.

Example: In .NET, SqlDataAdapter fills DataSet – it adapts the SQL DataReader to a disconnected data container. Also, the ConfigurationManager adapts different configuration sources.