봄맞이 세일
어댑터

Go로 작성된 어댑터

어댑터는 구조 디자인 패턴이며, 호환되지 않는 객체들이 협업할 수 있도록 합니다.

어댑터는 두 객체 사이의 래퍼 역할을 합니다. 하나의 객체에 대한 호출을 캐치하고 두 번째 객체가 인식할 수 있는 형식과 인터페이스로 변환합니다.

개념적인 예시

어떤 객체의 일부 기능들​(예: 라이트닝 포트)​을 기대하는 클라이언트가 있습니다. 그러나 또 adaptee(윈도우 랩톱)​라는 객체가 있습니다. 이 객체는 같은 기능성을 다른 인터페이스​(USB 포트)​를 통해 제공합니다.

어댑터 패턴은 이러한 상황에 사용할 수 있습니다. 이제 다음을 수행하는 라는 구조체 유형을 만듭니다:

  • 클라이언트가 기대하는 것과 같은 인터페이스​(라이트닝 포트)​를 준수.

  • 클라이언트의 요청을 adaptee가 예상하는 형식으로 변환합니다. 어댑터는 라이트닝 커넥터를 받아들인 다음 신호를 USB 형식으로 변환하고 윈도우 랩톱의 USB 포트로 전달합니다.

client.go: 클라이언트 코드

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: 클라이언트 인터페이스

package main

type Computer interface {
	InsertIntoLightningPort()
}

mac.go: 서비스

package main

import "fmt"

type Mac struct {
}

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

windows.go: 알려지지 않은 서비스

package main

import "fmt"

type Windows struct{}

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

windowsAdapter.go: 어댑터

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: 실행 결과

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.

다른 언어로 작성된 어댑터

C#으로 작성된 어댑터 C++로 작성된 어댑터 자바로 작성된 어댑터 PHP로 작성된 어댑터 파이썬으로 작성된 어댑터 루비로 작성된 어댑터 러스트로 작성된 어댑터 스위프트로 작성된 어댑터 타입스크립트로 작성된 어댑터