Adapter, as its name implies, connects incompatible interfaces together using a communicative class. This adapter is highly cohesive to one side of the interfaces. Adapter is also known as a "binding" or "wrapper".
In Go, it is very easy to use adapter. One just declares a converter function / create a adapter package to perform the conversion.
package main
import (
"fmt"
)
// Printer is the interface class
type Printer struct {
}
// Render is the actual printer function, taking *[]byte as input
func (p *Printer) Render(data *[]byte) {
fmt.Printf("The given data are: %v\n", data)
}
// StringAdapter is the converter between printer and string types
func (p *Printer) StringAdapter(str string) {
data := []byte(str)
p.Render(&data)
}
func main() {
p := &Printer{}
p.StringAdapter("Hello World")
}
// Output:
// The given data are: &[72 101 108 108 111 32 87 111 114 108 100]
Notice that the Printer
has a StringAdapter
function that converts string
data type into the *[]byte
data type for Render
function to run. The client does not need to explicitly convert the string data; The Printer has more cohesion by facilitating conversion adapter to its data input.