Adapter Pattern
Keep an application contract while adapting an existing API, including the meaning of its values.
· Last updated: 2026-11-07 · 14 min read
Overview
Just as a physical adapter joins devices with different connectors, a software adapter makes two different ways of using an object fit together. Only the connector differs; the job stays the same.
When a room monitor displays Celsius while an older sensor API returns Fahrenheit, both use numbers, so passing 86 straight through compiles cleanly while showing the wrong temperature. The monitor trusts that number to be Celsius. The caller needs code that converts to the unit it expects. Nothing at compile time marks the value as wrong.
What gets separated first is the call the monitor makes and the call the sensor offers, which do not match. The Adapter pattern makes an existing object usable through a different interface. An interface is the calling agreement: here, ReadCelsius() promises a Celsius reading. The old sensor stays untouched. The adapter holds a reference to it and takes on only the conversion.
Even if a Kelvin sensor replaces the old one, the monitor goes on calling ReadCelsius() as long as the new sensor has its own adapter. Whatever usage each sensor requires stays confined to that sensor's adapter. A swap then costs one adapter, not every caller.
UML
In the diagram, the same split appears as three classes. RoomMonitor is the caller and ICelsiusThermometer is the interface it needs. FahrenheitAdapter implements that interface and asks the existing LegacyThermometer to do the underlying work. Asking another object to carry out that work is delegation.
Reading the notation first makes the direction clear. Solid arrows show object references. A dashed line with a hollow triangle means interface implementation. Calls travel through RoomMonitor → FahrenheitAdapter → LegacyThermometer; on the way back, the adapter converts Fahrenheit to Celsius.
History
Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides cataloged Adapter as a structural pattern in Design Patterns, published in 1994. GoF refers to those four authors.1
Their example reuses an existing text-display component through a drawing editor's shape interface. The book distinguishes a class adapter, which uses inheritance, from an object adapter, which holds the adapted object. The UML and C# example here use the object form.2
A comparable library example is Java's InputStreamReader: it accepts a byte-oriented InputStream, decodes bytes according to a character encoding and presents a character-oriented Reader. Its documentation dates it to JDK 1.1, released in 1997. That is a concrete use of the structure, not a claim that Adapter was invented then.3
Why use it?
Suppose the screen, the logger, and the alarm each read the old sensor directly; all three would then need the Fahrenheit conversion and the details of how the external API is called. Every extra caller copies the same knowledge again. Replacing the sensor would mean editing all three, so the conversion belongs in one object that the rest of the code reaches through a shared contract.
Renaming a method is not the whole job: the return units, the argument order, the time zones, and the failure codes must all match what the caller expects. The same boundary test applies when wrapping a vendor's SDK. If a failed measurement becomes zero degrees, the caller takes the fault for a real reading. So what the adapter imitates is more than a signature.
There are also cases where an adapter is more machinery than the job needs. A conversion function is enough for one caller and one calculation. An adapter object earns its place when several callers share an interface or the external implementation has to be swappable. Adapter reconciles different calling contracts; Decorator keeps the contract and adds behavior on top. Facade is closer to bundling several sub-functions behind a single entry point.
Example
Assume the old sensor returns a fixed Fahrenheit value. This small example shows only the calls and the conversion, without contacting real hardware. The boundary between the two roles still shows.
using System;
using System.Globalization;
var legacy = new LegacyThermometer(86m);
ICelsiusThermometer sensor = new FahrenheitAdapter(legacy);
new RoomMonitor(sensor).Print();
// Consumers use a shared Celsius-reading contract rather than a sensor-specific API.
public interface ICelsiusThermometer
{
decimal ReadCelsius();
}
public sealed class LegacyThermometer
{
private readonly decimal fahrenheit;
public LegacyThermometer(decimal fahrenheit) => this.fahrenheit = fahrenheit;
public decimal ReadFahrenheit() => fahrenheit;
}
// Keep the Fahrenheit-to-Celsius conversion inside this adapter.
public sealed class FahrenheitAdapter : ICelsiusThermometer
{
private readonly LegacyThermometer legacy;
public FahrenheitAdapter(LegacyThermometer legacy) => this.legacy = legacy;
public decimal ReadCelsius() => (legacy.ReadFahrenheit() - 32m) * 5m / 9m;
}
public sealed class RoomMonitor
{
private readonly ICelsiusThermometer sensor;
public RoomMonitor(ICelsiusThermometer sensor) => this.sensor = sensor;
public void Print()
{
string value = sensor.ReadCelsius().ToString("F1", CultureInfo.InvariantCulture);
Console.WriteLine($"Room: {value} Celsius");
}
}Room: 30.0 CelsiusRoomMonitor.Print() calls ReadCelsius(). The adapter reads Fahrenheit and converts 86 °F to 30 °C with . Literals such as 5m use decimal, avoiding integer division. The caller contains neither the old sensor type nor the conversion formula. The conversion happens inside that one call.
An extended example
Two sensor APIs and explicit failures
A second sensor forces a decision about failure reporting. Now the application uses a Fahrenheit and a Kelvin sensor: the first returns a success flag, the second a number directly. The shapes differ, yet the caller need not know that, which is why ICelsiusThermometer returns the Celsius result plus the reason a measurement failed.
The result holds either a success value or an error code, never both. Reading.Success carries the Celsius value and Reading.Failure carries an error code. Offline is the state in which no measurement is possible at all, while InvalidReading is a value below absolute zero, which this example does not accept. From the caller's side, the same success and failure handling works no matter which sensor sits behind it.
using System;
using System.Globalization;
ICelsiusThermometer[] sensors =
{
new FahrenheitAdapter(new LegacySensor(86m, online: true)),
new KelvinAdapter(new KelvinSensor(300m)),
new FahrenheitAdapter(new LegacySensor(0m, online: false)),
new KelvinAdapter(new KelvinSensor(-1m))
};
foreach (ICelsiusThermometer sensor in sensors)
{
Reading result = sensor.ReadCelsius();
if (result is Reading.Success success)
Console.WriteLine("Celsius: " + success.Celsius.ToString("F2", CultureInfo.InvariantCulture));
if (result is Reading.Failure failure)
Console.WriteLine("Error: " + failure.Code);
}
public enum SensorError { Offline, InvalidReading }
public abstract record Reading
{
private Reading() { }
public sealed record Success(decimal Celsius) : Reading;
public sealed record Failure(SensorError Code) : Reading;
public static Reading FromCelsius(decimal value) => value < -273.15m
? new Failure(SensorError.InvalidReading)
: new Success(value);
}
// Consumers use a Celsius-or-failure contract rather than a sensor-specific API.
public interface ICelsiusThermometer
{
Reading ReadCelsius();
}
public sealed class LegacySensor
{
private readonly decimal fahrenheit;
private readonly bool online;
public int Calls { get; private set; }
public LegacySensor(decimal fahrenheit, bool online)
{
this.fahrenheit = fahrenheit;
this.online = online;
}
public bool TryRead(out decimal value)
{
Calls++;
value = fahrenheit;
return online;
}
}
public sealed class KelvinSensor
{
private readonly decimal kelvin;
public KelvinSensor(decimal kelvin) => this.kelvin = kelvin;
public decimal ReadKelvin() => kelvin;
}
// Translate the external API’s units and failure meaning inside this adapter.
public sealed class FahrenheitAdapter : ICelsiusThermometer
{
private readonly LegacySensor sensor;
public FahrenheitAdapter(LegacySensor sensor) => this.sensor = sensor;
public Reading ReadCelsius()
{
if (!sensor.TryRead(out decimal value))
return new Reading.Failure(SensorError.Offline);
if (value < -459.67m)
return new Reading.Failure(SensorError.InvalidReading);
return Reading.FromCelsius((value - 32m) / 9m * 5m);
}
}
public sealed class KelvinAdapter : ICelsiusThermometer
{
private readonly KelvinSensor sensor;
public KelvinAdapter(KelvinSensor sensor) => this.sensor = sensor;
public Reading ReadCelsius()
{
decimal value = sensor.ReadKelvin();
if (value < 0m)
return new Reading.Failure(SensorError.InvalidReading);
return Reading.FromCelsius(value - 273.15m);
}
}Celsius: 30.00
Celsius: 26.85
Error: Offline
Error: InvalidReadingDifferent failure signals from the two sensors converge into one shape as they pass through the adapters. Both adapters return the same result shape after converting the unit. An offline Fahrenheit sensor returns Offline without using its numeric value, and -1 K is rejected as InvalidReading. As a result, the caller can tell a valid measurement from a failure.
The adapter also owns the order in which the formula runs. The Fahrenheit adapter checks the accepted range first, then divides by 9 before multiplying by 5. That order keeps a very large decimal value from overflowing during the intermediate multiplication. The checks catch out-of-range input and communication failure, but they cannot tell whether a physical sensor measured accurately.
Scope
Decisions beyond the adapter's scope are left open like this. The adapters do not retry, reuse an earlier reading or return a default. If the application needs those behaviors, define which failures permit a retry, the attempt limit, or how long an old value remains acceptable.
The two sensor classes are stand-ins for the example. If a real SDK throws, translate the exception into the caller's error contract at that boundary, and handle cancellation, connection teardown, and device lifetime according to the real API. These are the points to revisit when the example meets real hardware.
TypeScript example
Each adapter takes on the unit conversion and the failure decisions for its own sensor, so the code that consumes temperatures receives only a Celsius result. This separation is meant to keep an external API change from forcing a formula edit in every display. The code that follows ports the two sensors and the failure results from the extended example to TypeScript. Only the language changes; the roles stay the same.
type Reading = { ok: true; celsius: number } |
{ ok: false; code: "Offline" | "InvalidReading" };
// Consumers use a Celsius-or-failure contract rather than a sensor-specific API.
interface ICelsiusThermometer { readCelsius(): Reading; }
class LegacySensor {
constructor(private readonly fahrenheit: number, private readonly online: boolean) {}
tryRead(): { online: boolean; value: number } {
return { online: this.online, value: this.fahrenheit };
}
}
class KelvinSensor {
constructor(private readonly kelvin: number) {}
readKelvin(): number { return this.kelvin; }
}
// Translate the external API’s units and failure meaning inside this adapter.
class FahrenheitAdapter implements ICelsiusThermometer {
constructor(private readonly sensor: LegacySensor) {}
readCelsius(): Reading {
const reading = this.sensor.tryRead();
if (!reading.online) return { ok: false, code: "Offline" };
if (!Number.isFinite(reading.value) || reading.value < -459.67)
return { ok: false, code: "InvalidReading" };
// Anchor at absolute zero so rounding does not push a valid boundary below it.
return { ok: true, celsius: (reading.value + 459.67) / 9 * 5 - 273.15 };
}
}
class KelvinAdapter implements ICelsiusThermometer {
constructor(private readonly sensor: KelvinSensor) {}
readCelsius(): Reading {
const value = this.sensor.readKelvin();
if (!Number.isFinite(value) || value < 0) return { ok: false, code: "InvalidReading" };
return { ok: true, celsius: value - 273.15 };
}
}
const sensors: ICelsiusThermometer[] = [
new FahrenheitAdapter(new LegacySensor(86, true)),
new KelvinAdapter(new KelvinSensor(300)),
new FahrenheitAdapter(new LegacySensor(0, false)),
new KelvinAdapter(new KelvinSensor(-1)),
];
for (const sensor of sensors) {
const result = sensor.readCelsius();
console.log(result.ok ? "Celsius: " + result.celsius.toFixed(2) : "Error: " + result.code);
}Celsius: 30.00
Celsius: 26.85
Error: Offline
Error: InvalidReadingOnly the arithmetic differs. Unlike C# decimal, number is binary floating point, so the displayed precision is set with toFixed(2). Invalid values and offline status likewise do not become zero degrees.
Connecting types with Adapter<TSource, TTarget>
Suppose an existing sensor returns a reading in thousandths of a degree, while callers expect a Reader<double> that supplies degrees Celsius. Adapter<TSource, TTarget> takes a source-reading function and a conversion function, exposing the Read() contract the caller expects. Here the same split is built from two functions instead of a sensor class.
The type parameters record in code that the two sides differ. TSource and TTarget may be different types. Here the adapter converts LegacyReading into double or number. The assembly code knows that the legacy method is named Measure() and that its unit needs conversion; callers only use Read().
C#
using System;
using System.Globalization;
var sensor = new LegacySensor();
IReader<double> reader = new Adapter<LegacyReading, double>(
sensor.Measure, value => value.MilliCelsius / 1000.0);
Console.WriteLine(reader.Read().ToString("F1", CultureInfo.InvariantCulture));
// TYPES
sealed record LegacyReading(int MilliCelsius);
sealed class LegacySensor
{
public LegacyReading Measure() => new(21500);
}
interface IReader<T> { T Read(); }
sealed class Adapter<TSource, TTarget> : IReader<TTarget>
{
private readonly Func<TSource> readSource;
private readonly Func<TSource, TTarget> convert;
public Adapter(Func<TSource> readSource, Func<TSource, TTarget> convert)
{ this.readSource = readSource; this.convert = convert; }
// Join the legacy read and conversion behind the target contract.
public TTarget Read() => convert(readSource());
}21.5TypeScript
type LegacyReading = Readonly<{ milliCelsius: number }>;
class LegacySensor {
measure(): LegacyReading { return { milliCelsius: 21500 }; }
}
interface Reader<T> { read(): T; }
class Adapter<TSource, TTarget> implements Reader<TTarget> {
constructor(
private readonly readSource: () => TSource,
private readonly convert: (value: TSource) => TTarget,
) {}
// Keep the legacy name and units outside the caller-facing Reader contract.
read(): TTarget { return this.convert(this.readSource()); }
}
const sensor = new LegacySensor();
const reader: Reader<number> = new Adapter<LegacyReading, number>(
() => sensor.measure(), value => value.milliCelsius / 1000,
);
console.log(reader.read().toFixed(1));21.5Matching types does not settle units or value ranges; the conversion function must implement those rules. This example only converts units, assuming the sensor supplies valid integer readings in thousandths of a degree.
The official references describe the type-parameter syntax and library contracts.4
Related reading
Footnotes
- Gamma, Helm, Johnson and Vlissides. Design Patterns (1994). Publisher record. ↩
- GoF. Adapter excerpt. Class and object adapters and reuse of a text-display component. ↩
- Oracle. InputStreamReader, Since 1.1. JVM release-history table, JDK 1.1: February 1997. ↩
- C# generics; TypeScript generics ↩