golang 适配器模式 简单示例

需求

有些时候我们做项目会需要切换不同的数据源,比如数据源是一个文本的形式存储的,这时候使用适配器模式就可以方便的切换,或者是在支付的场景,用户选择不同的支付方式的时候

直接上示例

Go 复制代码
package main
 
import (
    "fmt"
)
 
// Target 是客户端期望的接口
type Target interface {
    Request() string
}
 
// Adaptee1 是第一个需要适配的类
type Adaptee1 struct{}
 
func (a *Adaptee1) SpecificRequest1() string {
    return "Called SpecificRequest1()"
}
 
// Adapter1 是第一个适配器类
type Adapter1 struct {
    adaptee *Adaptee1
}
 
func (adapter *Adapter1) Request() string {
    return adapter.adaptee.SpecificRequest1()
}
 
// Adaptee2 是第二个需要适配的类
type Adaptee2 struct{}
 
func (a *Adaptee2) SpecificRequest2() string {
    return "Called SpecificRequest2()"
}
 
// Adapter2 是第二个适配器类
type Adapter2 struct {
    adaptee *Adaptee2
}
 
func (adapter *Adapter2) Request() string {
    return adapter.adaptee.SpecificRequest2()
}
 
// AdapterFactory 是适配器工厂
type AdapterFactory struct{}
 
// GetAdapter 根据条件返回不同的适配器
func (factory *AdapterFactory) GetAdapter(adapterType string) Target {
    switch adapterType {
    case "adapter1":
        return &Adapter1{&Adaptee1{}}
    case "adapter2":
        return &Adapter2{&Adaptee2{}}
    default:
        return nil
    }
}
 
func main() {
    factory := &AdapterFactory{}
    // 使用第一个适配器
    adapter1 := factory.GetAdapter("adapter1")
    fmt.Println(adapter1.Request()) // 输出: Called SpecificRequest1()
 
    // 切换到第二个适配器
    adapter2 := factory.GetAdapter("adapter2")
    fmt.Println(adapter2.Request()) // 输出: Called SpecificRequest2()
}

把上面代码放在 main.go 里面执行即可查看效果

相关推荐
sg_knight13 天前
适配器模式(Adapter)
python·设计模式·适配器模式·adapter
java干货20 天前
如何让 iPhone 用上 Type-C 充电器?适配器模式详解
c语言·iphone·适配器模式
驴儿响叮当201021 天前
设计模式之适配器模式
设计模式·适配器模式
沛沛老爹1 个月前
跨平台Agent Skills开发:适配器模式赋能提示词优化与多AI应用无缝集成
人工智能·agent·适配器模式·rag·企业转型·skills
Sivan_Xin1 个月前
拒绝 If-Else 屎山:利用适配器模式(Adapter)构建第三方登录的“防腐层”实战
linux·python·适配器模式
短剑重铸之日1 个月前
《设计模式》第七篇:适配器模式
java·后端·设计模式·适配器模式
小码过河.1 个月前
设计模式——适配器模式
设计模式·适配器模式
代码丰1 个月前
项目里接了多个第三方 SDK 后,如何使用适配器模式+策略模式优化?(Adapter + Strategy)
java·适配器模式·策略模式
懵萌长颈鹿1 个月前
适配器模式 (Adapter Pattern)
适配器模式
茶本无香1 个月前
设计模式之八: 适配器模式解释及应用
java·设计模式·适配器模式