适配器模式通过定义统一SMSSender接口,为阿里云和腾讯云短信服务分别实现AliyunAdapter和TencentAdapter适配器,使不同SDK接口标准化,业务层可透明切换服务商,提升扩展性与维护性。

在使用 Golang 开发项目时,经常会对接第三方服务,比如支付、短信、物流等。不同第三方接口的参数结构和方法命名可能差异较大,直接调用会导致代码耦合度高、难以维护。适配器模式能有效解决这类问题,通过统一接口屏蔽底层差异。
适配器模式允许将一个类的接口转换成客户端期望的另一个接口。它让原本由于接口不兼容而无法一起工作的类可以协同工作。
在对接多个第三方服务时,我们可以定义一个统一的内部接口,然后为每个第三方实现对应的适配器,使它们都符合这个标准接口。
假设我们需要支持阿里云和腾讯云两个短信服务商,它们的 SDK 调用方式不同:
立即学习“go语言免费学习笔记(深入)”;
阿里云需要 AccessKey 和 Secret,发送方法为 SendSms;我们希望上层业务无需关心具体实现,统一调用 Send 方法即可。
1. 定义统一接口首先定义一个标准化的短信发送接口:
type SMSSender interface {
Send(phone, message string) error
}
模拟阿里云和腾讯云的客户端:
type AliyunClient struct {
AccessKey string
Secret string
}
func (a *AliyunClient) SendSms(to string, content string) error {
// 模拟调用阿里云 API
fmt.Printf("[Aliyun] 发送短信到 %s: %s\n", to, content)
return nil
}
type TencentClient struct {
SDKAppID string
AppKey string
}
func (t *TencentClient) SendSMS(phoneNumbers []string, templateID string, params []string) error {
// 模拟调用腾讯云 API
fmt.Printf("[Tencent] 向 %v 发送模板短信,ID=%s\n", phoneNumbers, templateID)
return nil
}
为每个第三方服务编写适配器,使其满足 SMSSender 接口:
type AliyunAdapter struct {
client *AliyunClient
}
func NewAliyunAdapter(accessKey, secret string) *AliyunAdapter {
return &AliyunAdapter{
client: &AliyunClient{AccessKey: accessKey, Secret: secret},
}
}
func (a *AliyunAdapter) Send(phone, message string) error {
return a.client.SendSms(phone, message)
}
type TencentAdapter struct {
client *TencentClient
}
func NewTencentAdapter(appID, appKey string) *TencentAdapter {
return &TencentAdapter{
client: &TencentClient{SDKAppID: appID, AppKey: appKey},
}
}
func (t *TencentAdapter) Send(phone, message string) error {
// 假设使用固定模板 ID 和参数处理
return t.client.SendSMS([]string{phone}, "10086", []string{message})
}
业务层无需知道具体服务商细节:
func NotifyUser(sender SMSSender, phone string) {
sender.Send(phone, "您的订单已发货")
}
// 使用示例
func main() {
var sender SMSSender
// 可灵活切换
sender = NewAliyunAdapter("ak-xxx", "sk-yyy")
NotifyUser(sender, "13800138000")
sender = NewTencentAdapter("app123", "key456")
NotifyUser(sender, "13900139000")
}
适配器模式让系统更具扩展性:
这种模式特别适合需要集成多个外部 API 的中台服务或网关系统。
基本上就这些,关键在于抽象出稳定接口,把变化封装在适配器内部。
以上就是Golang适配器模式第三方接口兼容示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号