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 里面执行即可查看效果

相关推荐
禾川兴 132424006886 天前
国产芯片解析:龙讯HDMI Splitter系列:多屏共享高清
单片机·fpga开发·适配器模式
coderzpw7 天前
设计模式中的“万能转换器”——适配器模式
设计模式·适配器模式
十五年专注C++开发8 天前
设计模式之适配器模式(二):STL适配器
c++·设计模式·stl·适配器模式·包装器
Absinthe_苦艾酒9 天前
设计模式之适配器模式
设计模式·适配器模式
木子庆五9 天前
Android 设计模式之适配器模式
android·设计模式·适配器模式
系统工程实验室10 天前
系统架构设计-防腐层、门面模式和适配器模式
java·设计模式·适配器模式
胡耀超11 天前
跨语言微服务架构(Java、Python)——“API中台”
java·python·微服务·云原生·架构·适配器模式·api中台
小九没绝活21 天前
设计模式-适配器模式
java·设计模式·适配器模式
wenbin_java25 天前
设计模式之适配器模式:原理、实现与应用
java·设计模式·适配器模式
码农的天塌了25 天前
java设计模式之适配器模式
java·设计模式·适配器模式