What

Adapter is a structural design pattern that allows objects with incompatible interfaces to collaborate.

Translator.

Why

There are scenarios interfaces of different objects are different and cannot collaborate. An adapter is like a translator that enable them to use the same interface.

Example

Different Data File Formats

I am doing data analysis with data collected from multiple websites (in different formats, json, csv, xml, etc), I don’t want to rewrite my data analysis library. Instead of making the data analysis library/algorithm support multiple data types, why don’t we use adaptor/translator to make all data follow the same data structure.

image-20221029030300961

SocketIO Redis Adapter

Redis adapter | Socket.IO

Where

  • When the interface of multiple objects that need to collaborate aren’t the same.

Analogy

Here is an analogy. A Chinese and and French president are having a meeting, there is a Chinese translator who know Chinese and English, and a French translator who know French and English. Then the 2 translators can communicate through English. In this analogy, English language is the bidirectional channel. The 2 translators are the adapters, and the 2 presidents are the 2 environments.

graph TD
    subgraph Environment1[Environment 1]
        ChinesePresident[Chinese President] <--> ChineseTranslator[Chinese Translator]
    end

    subgraph ChannelLayer[Bidirectional Channel]
        English[English Language]
    end

    subgraph Environment2[Environment 2]
        FrenchTranslator[French Translator] <--> FrenchPresident[French President]
    end

    ChineseTranslator <--> English
    English <--> FrenchTranslator

    style ChinesePresident fill:#f9d5e5,stroke:#333
    style FrenchPresident fill:#f9d5e5,stroke:#333
    style ChineseTranslator fill:#d5e8f9,stroke:#333
    style FrenchTranslator fill:#d5e8f9,stroke:#333
    style English fill:#d5f9e8,stroke:#333
    style ChannelLayer fill:#f5f5f5,stroke-dasharray: 5 5

Reference