【Golang】设计模式 - Structural - Adapter

Posted by 西维蜀黍 on 2021-09-18, Last Modified on 2023-08-23

Adaptor Pattern

We have a client code that expects some features of an object (Lightning port), but we have another object called adaptee (Windows laptop) which offers the same functionality but through a different interface (USB port)

This is where the Adapter pattern comes into the picture. We create a struct type known as adapter that will:

  • Adhere to the same interface which the client expects (Lightning port).
  • Translate the request from the client to the adaptee in the form that the adaptee expects. The adapter accepts a Lightning connector and then translates its signals into a USB format and passes them to the USB port in windows laptop.

Refer to https://swsmile.info/post/design-pattern-adapter-pattern/ for Adapter pattern.

Example

client.go: Client code

package main

import "fmt"

type client struct {
}

func (c *client) insertLightningConnectorIntoComputer(com computer) {
    fmt.Println("Client inserts Lightning connector into computer.")
    com.insertIntoLightningPort()
}

computer.go: Client interface

package main

type computer interface {
    insertIntoLightningPort()
}

mac.go: Service

package main

import "fmt"

type mac struct {
}

func (m *mac) insertIntoLightningPort() {
    fmt.Println("Lightning connector is plugged into mac machine.")
}

windows.go: Unknown service

package main

import "fmt"

type windows struct{}

func (w *windows) insertIntoUSBPort() {
    fmt.Println("USB connector is plugged into windows machine.")
}

windowsAdapter.go: Adapter

package main

import "fmt"

type windowsAdapter struct {
    windowMachine *windows
}

func (w *windowsAdapter) insertIntoLightningPort() {
    fmt.Println("Adapter converts Lightning signal to USB.")
    w.windowMachine.insertIntoUSBPort()
}

main.go

package main

func main() {

    client := &client{}
    mac := &mac{}

    client.insertLightningConnectorIntoComputer(mac)

    windowsMachine := &windows{}
    windowsMachineAdapter := &windowsAdapter{
        windowMachine: windowsMachine,
    }

    client.insertLightningConnectorIntoComputer(windowsMachineAdapter)
}

output.txt: Execution result

Client inserts Lightning connector into computer.
Lightning connector is plugged into mac machine.
Client inserts Lightning connector into computer.
Adapter converts Lightning signal to USB.
USB connector is plugged into windows machine.

Reference