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

相关推荐
杯莫停丶11 小时前
设计模式之:适配器模式
设计模式·适配器模式
WaWaJie_Ngen12 小时前
【设计模式】适配器模式(Adapter)
设计模式·适配器模式
LoveXming1 天前
Chapter11—适配器模式
c++·设计模式·适配器模式·开闭原则
草莓熊Lotso3 天前
基于容器适配器模式的 Stack 与 Queue 实现:复用底层容器的优雅设计
c++·网络协议·rpc·适配器模式
Query*5 天前
Java 设计模式——适配器模式进阶:原理深挖、框架应用与实战扩展
java·设计模式·适配器模式
Query*6 天前
Java 设计模式——适配器模式:从原理到3种实战的完整指南
java·设计模式·适配器模式
Deschen10 天前
设计模式-适配器模式
java·设计模式·适配器模式
王嘉俊92512 天前
设计模式--适配器模式:优雅解决接口不兼容问题
java·设计模式·适配器模式
笨手笨脚の17 天前
设计模式-适配器模式
设计模式·适配器模式·结构型设计模式
青草地溪水旁17 天前
第六章:适配器模式 - 接口转换的艺术大师
c++·适配器模式