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

相关推荐
老朱佩琪!3 天前
Unity适配器模式
unity·设计模式·游戏引擎·适配器模式
有一个好名字5 天前
设计模式-适配器模式
设计模式·适配器模式
ZouZou老师12 天前
C++设计模式之适配器模式:以家具生产为例
java·设计模式·适配器模式
咨询QQ:48773927817 天前
一款基于.NET Core Web + Bootstrap的企业级快速后台开发框架。 内置模块如
适配器模式
雨中飘荡的记忆20 天前
设计模式之适配器模式详解
java·设计模式·适配器模式
口袋物联23 天前
设计模式之适配器模式在 C 语言中的应用(含 Linux 内核实例)
c语言·设计模式·适配器模式
明洞日记1 个月前
【设计模式手册008】适配器模式 - 让不兼容的接口协同工作
java·设计模式·适配器模式
老鼠只爱大米1 个月前
Java 设计模式之适配器模式:系统集成的万能接口
java·设计模式·适配器模式·adapter·java设计模式
小毛驴8501 个月前
软件设计模式-适配器模式
电脑·适配器模式
朝新_1 个月前
【统一功能处理】从入门到源码:拦截器学习指南(含适配器模式深度解读)
数据库·后端·mybatis·适配器模式·javaee