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

相关推荐
LoveC52113 天前
设计模式之适配器模式
设计模式·适配器模式
fouryears_2341716 天前
适配器模式——以springboot为例
java·spring boot·适配器模式
失散1316 天前
大型微服务项目:听书——多端重复提交订单问题&适配器模式实现不同支付方式的选择&零钱支付逻辑
分布式·微服务·rabbitmq·适配器模式
蝸牛ちゃん18 天前
设计模式(七)结构型:适配器模式详解
设计模式·系统架构·软考高级·适配器模式
Amagi.21 天前
Java设计模式-适配器模式
java·设计模式·适配器模式
Dxy123931021625 天前
Python适配器模式详解:让不兼容的接口协同工作
开发语言·python·适配器模式
Ares-Wang1 个月前
设计模式》》门面模式 适配器模式 区别
设计模式·适配器模式
不修×蝙蝠1 个月前
设计模式深度解析:单例、工厂、适配器与代理模式
单例模式·设计模式·代理模式·适配器模式·工厂
hqxstudying1 个月前
Java行为型模式---策略模式
java·开发语言·建造者模式·适配器模式·策略模式
vvilkim1 个月前
深入理解设计模式:适配器模式及其应用实践
适配器模式