Design Patterns | Adapter

Structural pattern - Adapter

It allows you to connect objects with different interfaces.

Use cases:

  • When you have existing classes, but its’ interfaces isn’t compatible with your code

Let’s imagine next situation:

You wanna stream your computer desktop(with VGA OUTPUT) on TV. You only have VGA connector. In case if your TV compatible with VGA you just need to plug in connector, otherwise you need to get an adapter which convert all your computer signals to proper destination.

  1. Define VGAClient. In this case this will be your connector with VGA output
  2. Define two types of devices that support VGA and HDMI Inputs
  3. Define two concrete classes of VGADevice and HDMIDevice
  4. Create and adapter that accepts hdmi signal and convert it to VGA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
type VgaClient struct{}

func (c *VgaClient) plugVgaToDevice(d VgaDevice) {
d.acceptVgaConnector()
}

type VgaDevice interface {
acceptVgaConnector()
}
type HdmiDevice interface {
acceptHdmiConnector()
}
type VgaDisplay struct{}

func (d *VgaDisplay) acceptVgaConnector() {
fmt.Println("Accepted vga connector")
}

type HdmiDisplay struct{}

func (d *HdmiDisplay) acceptHdmiConnector() {
fmt.Println("Accept hdmi connector")
}

type HdmiToVgaAdapter struct {
device VgaDevice
}

func (h *HdmiToVgaAdapter) acceptHdmiConnector() {
// convert signal from HDMI to VGA
h.device.acceptVgaConnector()
}