{"id":"6b08bd2f80884893657cc8de","slug":"adapter","title":"Adapter – how to get along with code that speaks another language","summary":"Adapter translates the interface of a foreign class into the interface your code expects. An example of integrating a third-party geocoding SDK in C#, TypeScript, Java, Go and Python.","servedLang":"en","availableLangs":["pl","en"],"topics":["adapter","facade","decorator","hexagonal-architecture"],"techs":["dotnet","typescript","java","go","python"],"tags":["gof","structural","adapter","integration","anti-corruption-layer"],"level":"beginner","kind":"article","access":"public","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":11,"stats":{"views":4,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:13:51.251Z","updatedAt":"2026-11-27T13:05:48.206Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"indigo","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"The Adapter design pattern – the problem of incompatible interfaces, object and class adapters, a UML diagram, code in C#, TypeScript, Java, Go and Python, the anti-corruption layer, examples from .NET, Java, Go, Python and Node.js.","wordCount":2049,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"A library does exactly what you need, but its API fits your code like a US plug fits a European socket. "},{"type":"text","text":"Adapter","marks":[{"type":"bold"}]},{"type":"text","text":" is a small intermediary class that accepts calls in your format and translates them into the format of the foreign code – so neither side has to change."}]},{"type":"callout","attrs":{"variant":"info","title":"In short"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Your code defines the interface it needs (a port); the adapter implements it."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Inside, the adapter calls the foreign class and translates data, units, errors and calling style."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Foreign types do not leak out of the adapter – switching providers means a new adapter, not a change to your logic."}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"the-problem-an-sdk-that-thinks-in-micro-degrees"},"content":[{"type":"text","text":"The problem: an SDK that thinks in micro-degrees"}]},{"type":"paragraph","content":[{"type":"text","text":"The pierogi place's delivery module plans courier routes, so it needs coordinates for customer addresses. We picked an external service, GeoNexus. Its SDK works, but it has its own habits: it returns latitude and longitude as integers in micro-degrees, signals errors with status codes instead of exceptions, and in its JavaScript version uses callbacks instead of promises. The first version looked like this:"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"route-planner.ts"},"content":[{"type":"text","text":"class RoutePlanner {\n  plan(order: Order): void {\n    sdk.lookup(order.address, \"PL\", (r) => {\n      if (r.status !== 200) return this.fail(order);\n      const lat = r.latE6 / 1_000_000; // GeoNexus details leak into the domain\n      const lng = r.lngE6 / 1_000_000;\n      this.addStop(order, lat, lng);\n    });\n  }\n}"}]},{"type":"paragraph","content":[{"type":"text","text":"GeoNexus details – units, status codes, calling style – spilled all over the route planning logic. Tests need a fake of the whole SDK, and when procurement negotiates a cheaper provider, the delivery module will have to be rewritten."}]},{"type":"heading","attrs":{"level":2,"id":"the-solution-an-interface-on-our-side-a-translator-in-between"},"content":[{"type":"text","text":"The solution: an interface on our side, a translator in between"}]},{"type":"paragraph","content":[{"type":"text","text":"First we describe what the delivery module needs "},{"type":"text","text":"in our own words","marks":[{"type":"bold"}]},{"type":"text","text":": a "},{"type":"text","text":"Geocoder","marks":[{"type":"code"}]},{"type":"text","text":" interface with a single "},{"type":"text","text":"locate(address)","marks":[{"type":"code"}]},{"type":"text","text":" method that returns "},{"type":"text","text":"Coordinates","marks":[{"type":"code"}]},{"type":"text","text":" in degrees or \"not found\". Then we write a "},{"type":"text","text":"GeoNexusAdapter","marks":[{"type":"code"}]},{"type":"text","text":" that implements this interface and, inside, calls the SDK and translates the result. Route planning knows only "},{"type":"text","text":"Geocoder","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"classDiagram\n  direction LR\n  class RoutePlanner {\n    +plan(order)\n  }\n  class Geocoder {\n    <<interface>>\n    +locate(address) Coordinates\n  }\n  class GeoNexusAdapter {\n    -client GeoNexusClient\n    +locate(address) Coordinates\n  }\n  class GeoNexusClient {\n    +lookup(query, country) LookupResult\n  }\n  RoutePlanner --> Geocoder\n  Geocoder <|.. GeoNexusAdapter\n  GeoNexusAdapter --> GeoNexusClient : translates calls","caption":"Object adapter: the delivery module knows only its own interface"}},{"type":"pullQuote","attrs":{"text":"Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.","author":"Gamma","role":"Helm, Johnson, Vlissides","source":"Design Patterns (1994)"}},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Role"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"In the example"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Responsibility"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Target"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Geocoder","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the interface the client expects"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Client"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"RoutePlanner","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"uses only the target"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Adaptee"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"GeoNexusClient","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"an existing class with an incompatible API"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Adapter"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"GeoNexusAdapter","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"implements the target, delegates to the adaptee and translates"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"The adapter translates much more than method names:"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Aspect"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"GeoNexus SDK"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Our interface"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Units"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"micro-degrees ("},{"type":"text","text":"50061700","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"degrees ("},{"type":"text","text":"50.0617","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"No result"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"status "},{"type":"text","text":"404","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"null","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"Optional.empty()","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"ErrNotFound","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Failure"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"another status"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"an exception or an error"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Calling style (JS)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"callback"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Promise","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Parameters"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"query + country code"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"just the address (the adapter sets the country)"}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"implementation-in-five-languages"},"content":[{"type":"text","text":"Implementation in five languages"}]},{"type":"paragraph","content":[{"type":"text","text":"This is an "},{"type":"text","text":"object","marks":[{"type":"bold"}]},{"type":"text","text":" adapter: it holds a reference to the SDK client and delegates to it. There is also a "},{"type":"text","text":"class","marks":[{"type":"bold"}]},{"type":"text","text":" adapter, which inherits from the adaptee and implements the target interface at the same time – it only works where you can inherit from the foreign class and it ties the adapter to one concrete implementation, so in practice composition wins. In Go the adapter does not even declare that it implements "},{"type":"text","text":"Geocoder","marks":[{"type":"code"}]},{"type":"text","text":" – having the right method is enough."}]},{"type":"codeGroup","attrs":{"title":"GeoNexusAdapter : Geocoder"},"content":[{"type":"codeBlock","attrs":{"language":"csharp","filename":"Geocoding.cs"},"content":[{"type":"text","text":"IGeocoder geocoder = new GeoNexusAdapter(new GeoNexusClient());\nvar shop = geocoder.Locate(\"Rynek Główny 1, Kraków\");\nConsole.WriteLine(shop is null ? \"not found\" : $\"{shop.Latitude}, {shop.Longitude}\");\n\n// Our port: what the delivery module needs, in our own vocabulary.\npublic sealed record Coordinates(double Latitude, double Longitude);\n\npublic interface IGeocoder\n{\n    Coordinates? Locate(string address);\n}\n\n// Third-party SDK (we cannot change it): micro-degrees and status codes.\npublic sealed record LookupResult(int Status, long LatE6, long LngE6);\n\npublic sealed class GeoNexusClient\n{\n    public LookupResult Lookup(string query, string countryCode) => query.Contains(\"Kraków\")\n        ? new LookupResult(200, 50_061_700, 19_937_300)\n        : new LookupResult(404, 0, 0);\n}\n\n// Adapter: implements our interface by translating calls to the SDK.\npublic sealed class GeoNexusAdapter(GeoNexusClient client) : IGeocoder\n{\n    private const double MicroDegrees = 1_000_000d;\n\n    public Coordinates? Locate(string address)\n    {\n        var result = client.Lookup(address, countryCode: \"PL\");\n        return result.Status switch\n        {\n            200 => new Coordinates(result.LatE6 / MicroDegrees, result.LngE6 / MicroDegrees),\n            404 => null,\n            _ => throw new InvalidOperationException($\"GeoNexus failed with status {result.Status}\"),\n        };\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"geocoding.ts"},"content":[{"type":"text","text":"// Our port: what the delivery module needs, in our own vocabulary.\ninterface Coordinates {\n  latitude: number;\n  longitude: number;\n}\n\ninterface Geocoder {\n  locate(address: string): Promise<Coordinates | null>;\n}\n\n// Third-party SDK (we cannot change it): callbacks, micro-degrees, status codes.\ntype LookupResult = { status: number; latE6: number; lngE6: number };\n\nclass GeoNexusClient {\n  lookup(query: string, country: string, done: (result: LookupResult) => void): void {\n    const result = query.includes(\"Kraków\")\n      ? { status: 200, latE6: 50_061_700, lngE6: 19_937_300 }\n      : { status: 404, latE6: 0, lngE6: 0 };\n    setTimeout(() => done(result), 10);\n  }\n}\n\n// Adapter: callback -> Promise, micro-degrees -> degrees, status codes -> null or Error.\nclass GeoNexusAdapter implements Geocoder {\n  constructor(private readonly client: GeoNexusClient) {}\n\n  locate(address: string): Promise<Coordinates | null> {\n    return new Promise((resolve, reject) => {\n      this.client.lookup(address, \"PL\", (r) => {\n        if (r.status === 200) resolve({ latitude: r.latE6 / 1e6, longitude: r.lngE6 / 1e6 });\n        else if (r.status === 404) resolve(null);\n        else reject(new Error(`GeoNexus failed with status ${r.status}`));\n      });\n    });\n  }\n}\n\nconst geocoder: Geocoder = new GeoNexusAdapter(new GeoNexusClient());\ngeocoder.locate(\"Rynek Główny 1, Kraków\").then((c) => console.log(c));"}]},{"type":"codeBlock","attrs":{"language":"java","filename":"Delivery.java"},"content":[{"type":"text","text":"import java.util.Optional;\n\n// Our port: what the delivery module needs, in our own vocabulary.\nrecord Coordinates(double latitude, double longitude) {}\n\ninterface Geocoder {\n    Optional<Coordinates> locate(String address);\n}\n\n// Third-party SDK (we cannot change it): micro-degrees and status codes.\nrecord LookupResult(int status, long latE6, long lngE6) {}\n\nclass GeoNexusClient {\n    LookupResult lookup(String query, String countryCode) {\n        return query.contains(\"Kraków\")\n            ? new LookupResult(200, 50_061_700, 19_937_300)\n            : new LookupResult(404, 0, 0);\n    }\n}\n\n// Adapter: implements our interface by translating calls to the SDK.\nfinal class GeoNexusAdapter implements Geocoder {\n    private static final double MICRO_DEGREES = 1_000_000d;\n    private final GeoNexusClient client;\n\n    GeoNexusAdapter(GeoNexusClient client) { this.client = client; }\n\n    @Override\n    public Optional<Coordinates> locate(String address) {\n        LookupResult r = client.lookup(address, \"PL\");\n        return switch (r.status()) {\n            case 200 -> Optional.of(new Coordinates(r.latE6() / MICRO_DEGREES, r.lngE6() / MICRO_DEGREES));\n            case 404 -> Optional.empty();\n            default -> throw new IllegalStateException(\"GeoNexus failed with status \" + r.status());\n        };\n    }\n}\n\npublic class Delivery {\n    public static void main(String[] args) {\n        Geocoder geocoder = new GeoNexusAdapter(new GeoNexusClient());\n        System.out.println(geocoder.locate(\"Rynek Główny 1, Kraków\"));\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"go","filename":"geocoding.go"},"content":[{"type":"text","text":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n// Coordinates and Geocoder are our port, in our own vocabulary.\ntype Coordinates struct{ Lat, Lng float64 }\n\nvar ErrNotFound = errors.New(\"address not found\")\n\ntype Geocoder interface {\n\tLocate(address string) (Coordinates, error)\n}\n\n// LookupResult and GeoNexusClient come from a third-party SDK we cannot change.\ntype LookupResult struct {\n\tStatus       int\n\tLatE6, LngE6 int64\n}\n\ntype GeoNexusClient struct{}\n\nfunc (GeoNexusClient) Lookup(query, country string) LookupResult {\n\tif strings.Contains(query, \"Kraków\") {\n\t\treturn LookupResult{Status: 200, LatE6: 50_061_700, LngE6: 19_937_300}\n\t}\n\treturn LookupResult{Status: 404}\n}\n\n// GeoNexusAdapter satisfies Geocoder implicitly by translating calls to the SDK.\ntype GeoNexusAdapter struct{ Client GeoNexusClient }\n\nfunc (a GeoNexusAdapter) Locate(address string) (Coordinates, error) {\n\tr := a.Client.Lookup(address, \"PL\")\n\tswitch r.Status {\n\tcase 200:\n\t\treturn Coordinates{Lat: float64(r.LatE6) / 1e6, Lng: float64(r.LngE6) / 1e6}, nil\n\tcase 404:\n\t\treturn Coordinates{}, ErrNotFound\n\tdefault:\n\t\treturn Coordinates{}, fmt.Errorf(\"geonexus: unexpected status %d\", r.Status)\n\t}\n}\n\nfunc main() {\n\tvar g Geocoder = GeoNexusAdapter{Client: GeoNexusClient{}}\n\tc, err := g.Locate(\"Rynek Główny 1, Kraków\")\n\tfmt.Println(c, err)\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"geocoding.py"},"content":[{"type":"text","text":"from dataclasses import dataclass\nfrom typing import Protocol\n\n\n@dataclass(frozen=True)\nclass Coordinates:\n    latitude: float\n    longitude: float\n\n\nclass Geocoder(Protocol):\n    \"\"\"Our port: what the delivery module needs, in our own vocabulary.\"\"\"\n\n    def locate(self, address: str) -> Coordinates | None: ...\n\n\nclass GeoNexusClient:\n    \"\"\"Third-party SDK we cannot change: dicts with micro-degrees and status codes.\"\"\"\n\n    def lookup(self, query: str, country_code: str) -> dict[str, int]:\n        if \"Kraków\" in query:\n            return {\"status\": 200, \"lat_e6\": 50_061_700, \"lng_e6\": 19_937_300}\n        return {\"status\": 404}\n\n\nclass GeoNexusAdapter:\n    \"\"\"Implements Geocoder by translating calls to the SDK.\"\"\"\n\n    def __init__(self, client: GeoNexusClient) -> None:\n        self._client = client\n\n    def locate(self, address: str) -> Coordinates | None:\n        result = self._client.lookup(address, country_code=\"PL\")\n        match result[\"status\"]:\n            case 200:\n                return Coordinates(result[\"lat_e6\"] / 1e6, result[\"lng_e6\"] / 1e6)\n            case 404:\n                return None\n            case status:\n                raise RuntimeError(f\"GeoNexus failed with status {status}\")\n\n\nif __name__ == \"__main__\":\n    geocoder: Geocoder = GeoNexusAdapter(GeoNexusClient())\n    print(geocoder.locate(\"Rynek Główny 1, Kraków\"))"}]}]},{"type":"callout","attrs":{"variant":"tip","title":"Adapter in tests"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Since the delivery module depends only on "},{"type":"text","text":"Geocoder","marks":[{"type":"code"}]},{"type":"text","text":", tests plug in a "},{"type":"text","text":"FakeGeocoder","marks":[{"type":"code"}]},{"type":"text","text":" with an address → coordinates table. Separately, in a few integration tests, you check the adapter itself against the provider's sandbox: does it convert units correctly and map status codes?"}]}]},{"type":"heading","attrs":{"level":2,"id":"step-by-step"},"content":[{"type":"text","text":"Step by step"}]},{"type":"timeline","attrs":{"items":[{"date":"Step 1","title":"Describe the client's need","text":"An interface in your domain's language – only the operations and types you actually use."},{"date":"Step 2","title":"Write the adapter","text":"A class that implements the interface and holds a reference to the foreign object."},{"date":"Step 3","title":"Translate data and errors","text":"Units, date formats, status codes, provider exceptions, calling style."},{"date":"Step 4","title":"Keep foreign types inside the adapter","text":"No SDK type appears in the interface signatures or in the domain."},{"date":"Step 5","title":"Wire it in the composition root","text":"The DI container or startup code binds the interface to the adapter."}]}},{"type":"heading","attrs":{"level":2,"id":"when-to-use-it-and-when-not-to"},"content":[{"type":"text","text":"When to use it and when not to"}]},{"type":"prosCons","attrs":{"pros":["integrating foreign code without changing it and without changing your own logic","provider details enclosed in one place","switching providers means a new adapter, not rewriting a module","easy testing with fakes of your own interface"],"cons":["another layer of indirection and a few extra types","an adapter to a very large API becomes large itself","mirroring the foreign API too literally carries its problems into your domain"],"prosTitle":"Pros","consTitle":"Cons"}},{"type":"paragraph","content":[{"type":"text","text":"Adapter is the natural choice when integrating external libraries, legacy systems, other teams' APIs, and anywhere you want the option to switch providers. It makes no sense when you can simply change both interfaces because you own them – then unify them instead."}]},{"type":"callout","attrs":{"variant":"warning","title":"A common mistake"},"content":[{"type":"paragraph","content":[{"type":"text","text":"An \"adapter\" interface that copies the provider's API – "},{"type":"text","text":"lookup(query, countryCode): LookupResult","marks":[{"type":"code"}]},{"type":"text","text":" – isolates nothing; it only renames the dependency. Start from the client's need, not from what the SDK can do. A good test: could a second provider be plugged into the same interface without changing it?"}]}]},{"type":"heading","attrs":{"level":2,"id":"related-patterns"},"content":[{"type":"text","text":"Related patterns"}]},{"type":"paragraph","content":[{"type":"text","text":"Adapter is literally the \"adapter\" of "},{"type":"text","text":"hexagonal architecture","marks":[{"type":"link","attrs":{"href":"/en/topics/hexagonal-architecture"}}]},{"type":"text","text":": the application core defines the port, and the adapter plugs the outside world into it. At the level of whole systems, a large adapter is called an anti-corruption layer. "},{"type":"text","text":"Facade","marks":[{"type":"link","attrs":{"href":"/en/topics/facade"}}]},{"type":"text","text":" hides foreign code too, but it simplifies many classes into one convenient interface instead of fitting one interface to another. "},{"type":"text","text":"Decorator","marks":[{"type":"link","attrs":{"href":"/en/topics/decorator"}}]},{"type":"text","text":" wraps an object without changing its interface, only adding behaviour, and "},{"type":"text","text":"Proxy","marks":[{"type":"link","attrs":{"href":"/en/topics/proxy"}}]},{"type":"text","text":" keeps the same interface and controls access."}]},{"type":"linkCard","attrs":{"url":"/en/topics/facade","title":"Facade","description":"A simple interface to many classes of a subsystem","kind":"topic","ref":"facade"}},{"type":"linkCard","attrs":{"url":"/en/topics/decorator","title":"Decorator","description":"The same interface, additional behaviour","kind":"topic","ref":"decorator"}},{"type":"linkCard","attrs":{"url":"/en/topics/hexagonal-architecture","title":"Hexagonal Architecture","description":"Ports and adapters across a whole application","kind":"topic","ref":"hexagonal-architecture"}},{"type":"heading","attrs":{"level":2,"id":"in-practice"},"content":[{"type":"text","text":"In practice"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":".NET","marks":[{"type":"bold"}]},{"type":"text","text":" – "},{"type":"text","text":"StreamReader","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"StreamWriter","marks":[{"type":"code"}]},{"type":"text","text":" adapt a byte stream ("},{"type":"text","text":"Stream","marks":[{"type":"code"}]},{"type":"text","text":") to a text API; packages such as "},{"type":"text","text":"Serilog.Extensions.Logging","marks":[{"type":"code"}]},{"type":"text","text":" adapt third-party logging libraries to "},{"type":"text","text":"ILogger","marks":[{"type":"code"}]},{"type":"text","text":" from "},{"type":"text","text":"Microsoft.Extensions.Logging","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Java","marks":[{"type":"bold"}]},{"type":"text","text":" – "},{"type":"text","text":"InputStreamReader","marks":[{"type":"code"}]},{"type":"text","text":" turns a byte stream into a character stream, "},{"type":"text","text":"Arrays.asList()","marks":[{"type":"code"}]},{"type":"text","text":" exposes an array as a "},{"type":"text","text":"List","marks":[{"type":"code"}]},{"type":"text","text":", and in Spring MVC "},{"type":"text","text":"HandlerAdapter","marks":[{"type":"code"}]},{"type":"text","text":" lets the "},{"type":"text","text":"DispatcherServlet","marks":[{"type":"code"}]},{"type":"text","text":" invoke very different kinds of handlers in one uniform way."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Go","marks":[{"type":"bold"}]},{"type":"text","text":" – "},{"type":"text","text":"http.HandlerFunc","marks":[{"type":"code"}]},{"type":"text","text":" adapts an ordinary function to the "},{"type":"text","text":"http.Handler","marks":[{"type":"code"}]},{"type":"text","text":" interface; "},{"type":"text","text":"strings.NewReader","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"bytes.NewReader","marks":[{"type":"code"}]},{"type":"text","text":" adapt a string and a byte slice to "},{"type":"text","text":"io.Reader","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Python","marks":[{"type":"bold"}]},{"type":"text","text":" – "},{"type":"text","text":"io.TextIOWrapper","marks":[{"type":"code"}]},{"type":"text","text":" wraps a binary stream and exposes it as a text stream, handling encoding and line endings."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Node.js","marks":[{"type":"bold"}]},{"type":"text","text":" – "},{"type":"text","text":"util.promisify()","marks":[{"type":"code"}]},{"type":"text","text":" adapts callback-style functions to the world of "},{"type":"text","text":"Promise","marks":[{"type":"code"}]},{"type":"text","text":" – exactly what our TypeScript adapter does."}]}]}]},{"type":"resourceRef","attrs":{"resourceId":"6b0854ad1a40d7e6c24c8eba"}},{"type":"heading","attrs":{"level":2,"id":"quick-check"},"content":[{"type":"text","text":"Quick check"}]},{"type":"quiz","attrs":{"question":"How does Adapter differ from Facade?","multiple":false,"options":[{"text":"Adapter fits an existing interface to an expected one, Facade simplifies access to many classes","correct":true,"explanation":"Yes – an adapter translates one interface into another, a facade creates a new, simpler entry point to a subsystem."},{"text":"Adapter always uses inheritance, Facade uses composition","correct":false,"explanation":"The object adapter, the most common one, uses composition."},{"text":"There is no difference – they are two names for the same pattern","correct":false,"explanation":"They have different goals: fitting interfaces versus simplifying a subsystem."}]}},{"type":"details","content":[{"type":"detailsSummary","content":[{"type":"text","text":"Interview question: object adapter or class adapter?"}]},{"type":"detailsContent","content":[{"type":"paragraph","content":[{"type":"text","text":"A "},{"type":"text","text":"class","marks":[{"type":"bold"}]},{"type":"text","text":" adapter inherits from the adaptee and implements the target interface. It can override the adaptee's behaviour, but it works only with that one class (not its subclasses), requires multiple inheritance or interfaces, and exposes the adaptee's public methods. An "},{"type":"text","text":"object","marks":[{"type":"bold"}]},{"type":"text","text":" adapter holds a reference and delegates – it works with any implementation of the adaptee, is easy to test and does not couple class hierarchies. The default choice is the object adapter, in line with \"composition over inheritance\"."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"summary"},"content":[{"type":"text","text":"Summary"}]},{"type":"paragraph","content":[{"type":"text","text":"Adapter lets you use foreign code on your own terms: the interface describes your domain's need, and the translation of units, errors and calling style is enclosed in a single class. It is the first structural pattern on the path. The next one – "},{"type":"text","text":"Bridge","marks":[{"type":"link","attrs":{"href":"/en/articles/bridge"}}]},{"type":"text","text":" – shows how to separate two axes of change before the number of classes gets out of hand."}]}]},"toc":[{"id":"the-problem-an-sdk-that-thinks-in-micro-degrees","text":"The problem: an SDK that thinks in micro-degrees","level":2,"locked":false},{"id":"the-solution-an-interface-on-our-side-a-translator-in-between","text":"The solution: an interface on our side, a translator in between","level":2,"locked":false},{"id":"implementation-in-five-languages","text":"Implementation in five languages","level":2,"locked":false},{"id":"step-by-step","text":"Step by step","level":2,"locked":false},{"id":"when-to-use-it-and-when-not-to","text":"When to use it and when not to","level":2,"locked":false},{"id":"related-patterns","text":"Related patterns","level":2,"locked":false},{"id":"in-practice","text":"In practice","level":2,"locked":false},{"id":"quick-check","text":"Quick check","level":2,"locked":false},{"id":"summary","text":"Summary","level":2,"locked":false}],"locked":false,"paywall":null,"previewRatio":0.3,"totalBlocks":36,"visibleBlocks":36,"resources":[{"id":"6b0857a63c96f2d34d0b3221","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=2PKQtcJjYvc","embedUrl":"https://www.youtube-nocookie.com/embed/2PKQtcJjYvc","title":"Adapter Pattern – Design Patterns (ep 8)","description":"","author":"Christopher Okhravi","thumbnailUrl":"https://i.ytimg.com/vi/2PKQtcJjYvc/hqdefault.jpg","durationSec":null,"lang":"en","topics":["adapter"],"techs":["general"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"seed","publishedAt":null,"popularity":0,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:37.974Z","updatedAt":"2026-11-26T16:00:37.974Z"},{"id":"6b0857c83c96f2d34d0b4a23","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=hTC3rmRBIxs","embedUrl":"https://www.youtube-nocookie.com/embed/hTC3rmRBIxs","title":"Proxy vs Adapter vs Facade Pattern | Code Walks 012","description":"What is really the difference between the proxy pattern, adapter pattern, and the facade pattern? ► 01:50 Common denominator ► 02:36 The quick explanation ► 03:20 Proxy pattern ► 04:59 Adapter pattern ► 07:10 Facade pattern ARTICLE MENTIONED ►…","author":"Christopher Okhravi","thumbnailUrl":"https://i.ytimg.com/vi/hTC3rmRBIxs/hqdefault.jpg","durationSec":null,"lang":"en","topics":["adapter","facade","proxy"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2016-07-16T09:26:16.000Z","popularity":58,"verifiedAt":"2026-11-26T10:57:20.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:10.095Z","updatedAt":"2026-11-26T16:01:10.095Z"},{"id":"6b0857bf3c96f2d34d0b425e","type":"article","provider":"web","url":"https://learn.microsoft.com/en-us/azure/architecture/patterns/anti-corruption-layer","embedUrl":null,"title":"Anti-Corruption Layer Pattern","description":"Learn about the Anti-Corruption Layer pattern. Implement a facade or adapter layer between a modern application and a legacy system.","author":"Microsoft Azure Architecture Center","thumbnailUrl":"https://learn.microsoft.com/en-us/media/open-graph-image.png","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["azure","cloud","legacy-code"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":65,"verifiedAt":"2026-11-26T11:07:40.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857be3c96f2d34d0b41e5","type":"article","provider":"web","url":"https://refactoring.guru/design-patterns/adapter","embedUrl":null,"title":"Adapter","description":"Adapter is a structural design pattern that allows objects with incompatible interfaces to collaborate.","author":"Refactoring.Guru","thumbnailUrl":"https://refactoring.guru/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868","durationSec":null,"lang":"en","topics":["adapter"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":75,"verifiedAt":"2026-11-26T11:26:01.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:59.965Z","updatedAt":"2026-11-26T16:00:59.965Z"},{"id":"6b0857c33c96f2d34d0b4658","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL6030812W","embedUrl":null,"title":"Design Patterns: Elements of Reusable Object-Oriented Software","description":"","author":"Erich Gamma, John Vlissides, Richard Helm, Ralph Johnson","thumbnailUrl":"https://covers.openlibrary.org/b/id/6601119-L.jpg","durationSec":null,"lang":"en","topics":["factory-method","abstract-factory","builder","prototype","singleton","adapter","bridge","composite","decorator","facade","flyweight","proxy","chain-of-responsibility","command","iterator","mediator","memento","observer","state","strategy","template-method","visitor"],"techs":["general"],"tags":["book","design-patterns"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"1995-01-01T00:00:00.000Z","popularity":71,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"}],"challenges":[{"id":"6b0857af5a2625e44ecaad13","slug":"design-patterns-basics-quiz","title":"Design patterns – basics","summary":"Six questions about classic GoF patterns: groups, intent and differences.","servedLang":"en","availableLangs":["pl","en"],"kind":"quiz","category":null,"status":"published","difficulty":"easy","topics":["builder","adapter","strategy","decorator","composite","facade","observer"],"techs":["general"],"tags":["quiz","gof","basics"],"languages":[],"questionCount":6,"xp":10,"stats":{"attempts":1,"solves":1,"solutions":0,"comments":0},"solveRate":100,"publishedAt":"2026-11-26T16:00:47.960Z"},{"id":"6b093dddbd4755deb67ee061","slug":"debounce-throttle","title":"Debounce and throttle","summary":"Two classic frontend higher-order functions – debounce (call after silence) and throttle (at most once per period) – with cancel, flush, preserved this and injected timers.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"medium","topics":["decorator"],"techs":["typescript","javascript"],"tags":["javascript","closures","timers","event-loop","higher-order-functions"],"languages":["typescript","javascript"],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:53.681Z"}],"attachments":[],"hasCode":true,"repoUrl":null,"series":[{"slug":"gof-structural","title":"GoF structural patterns","items":[{"slug":"adapter","title":"Adapter – how to get along with code that speaks another language","current":true},{"slug":"bridge","title":"Bridge – two axes of change without a class explosion","current":false},{"slug":"composite","title":"Composite – trees in which a leaf and a branch look the same","current":false},{"slug":"decorator","title":"Decorator – adding behaviour layer by layer","current":false},{"slug":"facade","title":"Facade – one simple entry point to a complex subsystem","current":false},{"slug":"flyweight","title":"Flyweight – how to fit 60,000 stadium seats in memory","current":false},{"slug":"proxy","title":"Proxy – a stand-in that controls access to the real object","current":false}]}],"prev":null,"next":{"slug":"bridge","title":"Bridge – two axes of change without a class explosion"},"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":38}]}}