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

在使用 Golang 开发项目时,经常会对接第三方服务,比如支付、短信、物流等。不同第三方接口的参数结构和方法命名可能差异较大,直接调用会导致代码耦合度高、难以维护。适配器模式能有效解决这类问题,通过统一接口屏蔽底层差异。
适配器模式核心思想
适配器模式允许将一个类的接口转换成客户端期望的另一个接口。它让原本由于接口不兼容而无法一起工作的类可以协同工作。
在对接多个第三方服务时,我们可以定义一个统一的内部接口,然后为每个第三方实现对应的适配器,使它们都符合这个标准接口。
场景:短信发送服务适配
假设我们需要支持阿里云和腾讯云两个短信服务商,它们的 SDK 调用方式不同:
立即学习“go语言免费学习笔记(深入)”;
阿里云需要 AccessKey 和 Secret,发送方法为 SendSms;
腾讯云使用 SDKappID 和密钥,调用方式为 SendSMS。
我们希望上层业务无需关心具体实现,统一调用 Send 方法即可。
1. 定义统一接口
首先定义一个标准化的短信发送接口:
type SMSSender interface { Send(phone, message string) error }
2. 模拟第三方服务结构体
模拟阿里云和腾讯云的客户端:
type AliyunClient struct { AccessKey string Secret string } func (a *AliyunClient) SendSms(to string, content string) error { // 模拟调用阿里云 API fmt.Printf("[Aliyun] 发送短信到 %s: %sn", 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=%sn", phoneNumbers, templateID) return nil }
3. 实现适配器
为每个第三方服务编写适配器,使其满足 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}) }
4. 上层调用示例
业务层无需知道具体服务商细节:
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") }
优势与适用场景
适配器模式让系统更具扩展性:
- 新增短信服务商时,只需实现适配器,不影响已有逻辑
- 测试时可轻松替换为 mock 适配器
- 统一错误处理、日志记录等横切关注点可在适配层集中管理
这种模式特别适合需要集成多个外部 API 的中台服务或网关系统。
基本上就这些,关键在于抽象出稳定接口,把变化封装在适配器内部。


