DEV Community

loading...
Cover image for Adapter Pattern πŸ”Œ

Adapter Pattern πŸ”Œ

shubhamzanwar profile image Shubham Zanwar Originally published at shubhamzanwar.com ・3 min read

The Adapter pattern is a structural design pattern. It allows 2 or more incompatible objects to interface with each other.

The first thing that comes to mind it probably the adapters for wall-sockets that allow your Indian phone charger to fit into European wall sockets! πŸ˜‚ That's exactly what adapters are. They are wrapper classes written around non-uniform classes so that the end result exposes a uniform API.

In case this is difficult to grasp, the following example should help:

This tutorial uses go. You can find the implementation here. However, if you read through it, I'm confident that you will be able to implement it in any programming language πŸ€—

Translator example

Consider that you're a regular english speaking person who has just migrated to Spain. πŸ‡ͺπŸ‡Έ
Your neighbour is a pleasant looking person and you'd like to be friends with this individual. However, there's one problem. 😨

Every one in your neighbourhood speaks Español exclusively. Oh, also, you don't speak Spanish 😞

In order to communicate with your potential friend, you would need some sort of translator to help convert your speech from English to Spanish. In programming terms, this translator is what we call an adapter!

Let's understand at how this would look in code.

As a first step, let's create the interface that a normal Spanish-speaking person would implement along with the structs for both, the Spanish and the English speaking person.

type SpeakSpanish interface {
    greetInSpanish() string
}

// Notice that the SpanishSpeaker already implements the
// SpeakSpanish interface
type SpanishSpeaker struct {}

func (s *SpanishSpeaker) greetInSpanish() string {
    return "Β‘Hola!"
}

type EnglishSpeaker struct {}

func (e *EnglishSpeaker) greetInEnglish() string {
    return "Hello there!"
}

As you can see, the SpanishSpeaker already implements the SpeakSpanish interface. However, the EnglishSpeaker does not have a greetInSpanish function and hence, doesn't implement the SpeakSpanish interface.

Let's use the adapter pattern to write a wrapper over the EnglishSpeaker that would give it the ability to greet in spanish.

type EnglishToSpanishAdapter {
    speaker EnglishSpeaker
}

func (a *EnglishToSpanishAdapter) greetInSpanish() string {
    const englishMessage = a.speaker.greetInEnglish();
    return translate(englishMessage)
}

func translate(engMessage string) spanishMessage string {
    // *insert complex translation logic*
    spanishMessage = "Β‘Hola!"
    return
}

Closely observing the adapter will show you that since it is a struct and has the greetInSpanish method, it implements the SpeakSpanish interface. This is good because once we wrap our english speaker in this adapter, we essentially get a Spanish speaker.

Also notice that we have a translation function as a util along with the adapter. Normally, you would use some service, like google translate, to translate the messages

Now, our Adapter module is complete. Amazing! πŸ”₯🀘🏽

Let's test it out and see it in action.

func main() {
    espanol := SpanishSpeaker{}
    englishwoman := EnglishSpeaker{}

    fmt.Println("Without translation:")
    fmt.Println("EspaΓ±ol says: ", espanol.greetInSpanish())
    fmt.Println("English Woman says: ", englishwoman.greetInEnglish())

    adaptedEnglishwoman := EnglishToSpanishAdapter{
        speaker: englishwoman,
    }

    fmt.Println("------------")
    fmt.Println("With translation:")
    fmt.Println("EspaΓ±ol says: ", espanol.greetInSpanish())
    fmt.Println("English Woman says: ", adaptedEnglishwoman.greetInSpanish())
}

As a result of this, you should see something like this in the terminal:

Without translation:
EspaΓ±ol says:  Β‘Hola!
English Woman says:  Hello there
------------
With translation:
EspaΓ±ol says:  Β‘Hola!
English Woman says:  Β‘Hola!

Hurray! The translation worked; the english woman and Spanish dude can now be friends! πŸ‘©πŸ»β€πŸ€β€πŸ‘¨πŸΎ

Design patterns save the day, yet again πŸš€πŸ˜

You can find all the code for this tutorial on this github repo

Cheers β˜•οΈ

Discussion

pic
Editor guide