[设计模式 Go实现] 结构型~适配器模式

适配器模式用于转换一种接口适配另一种接口。

实际使用中Adaptee一般为接口,并且使用工厂函数生成实例。

在Adapter中匿名组合Adaptee接口,所以Adapter类也拥有SpecificRequest实例方法,又因为Go语言中非入侵式接口特征,其实Adapter也适配Adaptee接口。

adapter.go
go 复制代码
package adapter

//Target 是适配的目标接口
type Target interface {
    Request() string
}

//Adaptee 是被适配的目标接口
type Adaptee interface {
    SpecificRequest() string
}

//NewAdaptee 是被适配接口的工厂函数
func NewAdaptee() Adaptee {
    return &adapteeImpl{}
}

//AdapteeImpl 是被适配的目标类
type adapteeImpl struct{}

//SpecificRequest 是目标类的一个方法
func (*adapteeImpl) SpecificRequest() string {
    return "adaptee method"
}

//NewAdapter 是Adapter的工厂函数
func NewAdapter(adaptee Adaptee) Target {
    return &adapter{
        Adaptee: adaptee,
    }
}

//Adapter 是转换Adaptee为Target接口的适配器
type adapter struct {
    Adaptee
}

//Request 实现Target接口
func (a *adapter) Request() string {
    return a.SpecificRequest()
}
adapter_test.go
go 复制代码
package adapter

import "testing"

var expect = "adaptee method"

func TestAdapter(t *testing.T) {
    adaptee := NewAdaptee()
    target := NewAdapter(adaptee)
    res := target.Request()
    if res != expect {
        t.Fatalf("expect: %s, actual: %s", expect, res)
    }
}
相关推荐
我爱cope11 小时前
【Agent智能体26 | 多智能体-多智能体工作流】
人工智能·设计模式·语言模型·职场和发展
小小龙学IT12 小时前
Go 泛型深度解析:从设计哲学到工程实践
服务器·数据库·golang
张忠琳14 小时前
【Go 1.26.4】(Part 2) Go 1.26.4 超深度分析 — Runtime GMP 调度器 (proc.go + runtime2.go)
开发语言·golang
踏着七彩祥云的小丑18 小时前
Go学习第5天:变量作用域 + 数组 + 指针
开发语言·学习·golang·go
咖啡八杯18 小时前
【无标题】
java·后端·设计模式
Lewiis19 小时前
白话桶排序
数据结构·算法·golang·排序算法
咖啡星人k19 小时前
MonkeyCode 后端架构全解析:Go微服务如何支撑万级并发AI任务
微服务·架构·golang·monkeycode
张忠琳19 小时前
【Go 1.26.4】Golang Interface 接口深度解析
开发语言·golang
伊灵eLing20 小时前
GoLang 语言高级(1)
开发语言·后端·golang
张忠琳20 小时前
【Go 1.26.4】(Part 8) Go 1.26.4 超深度分析 — context + reflect + errors
开发语言·golang