5、适配器模式

适配器模式(Adapter)允许不兼容的接口一起工作。在Go中,可以使用结构体嵌入和接口实现适配器模式:

定义

package adapter

import "fmt"

// 目标接口
type Target interface {
    Request() string
}

// 已存在的接口(不兼容)
type Adaptee struct{}

// 已存在的方法
func (a Adaptee) SpecificRequest() string {
    return "适配者的特殊请求"
}

// 适配器实现Target接口
type Adapter struct {
    adaptee Adaptee
}

// 适配器将SpecificRequest转换为Request
func (a Adapter) Request() string {
    fmt.Println("适配器转换请求...")
    return a.adaptee.SpecificRequest()
}

使用

// main.go
package main

import (
    "fmt"
    "myapp/adapter"
)

// 使用Target接口的客户端代码
func ClientCode(target adapter.Target) {
    result := target.Request()
    fmt.Println("客户端收到:", result)
}

func main() {
    // 创建适配者
    adaptee := adapter.Adaptee{}
    
    // 创建适配器
    adapter := adapter.Adapter{adaptee}
    
    // 使用适配器
    ClientCode(adapter)
}