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

相关推荐
JAVA坚守者4 天前
Java 性能调优全解析:从设计模式到 JVM 的 7 大核心方向实践
适配器模式·并发编程·jvm 调优·javacc·熔断机制·java 性能优化·jmh 测试
wjm04100614 天前
C++八股--5--设计模式--适配器模式,代理模式,观察者模式
c++·设计模式·适配器模式
催眠大树14 天前
适配器模式(Adapter Pattern)
java·开发语言·适配器模式
帝锦_li16 天前
Java进阶--设计模式
观察者模式·单例模式·代理模式·抽象工厂模式·适配器模式·原型模式
星星点点洲22 天前
【设计模式区别】装饰器模式和适配器模式区别
设计模式·适配器模式·装饰器模式
?abc!22 天前
设计模式基础概念(结构型模式):适配器模式(Adapter Pattern)
python·设计模式·适配器模式
碎梦归途24 天前
23种设计模式-结构型模式之适配器模式(Java版本)
java·开发语言·jvm·单例模式·设计模式·适配器模式
不当菜虚困1 个月前
JAVA设计模式——(1)适配器模式
java·设计模式·适配器模式
十五年专注C++开发1 个月前
面试题:C++11在C++98基础上增加了哪些内容?
开发语言·c++·设计模式·面试·stl·适配器模式
编程侦探1 个月前
【设计模式】适配器模式:让不兼容的接口和谐共处
开发语言·c++·设计模式·适配器模式