工厂模式通过封装对象创建逻辑,提升代码解耦与扩展性。1. 简单工厂使用函数根据参数返回不同实现,如支付方式选择;2. 抽象工厂支持多产品族,如不同地区支付与通知组合;3. 适用于数据库驱动、缓存、配置加载等场景。

在Go语言中,Factory(工厂)模式是一种创建型设计模式,用于解耦对象的创建逻辑。当需要根据不同的条件创建不同类型的对象时,使用工厂模式可以避免在代码中频繁使用 if-else 或 switch 判断,提升可维护性和扩展性。
什么是工厂模式
工厂模式的核心思想是:将对象的实例化过程封装到一个函数或方法中,调用者无需关心具体实现类型,只需通过统一接口获取所需对象。
在Go中,由于没有类和构造函数的概念,通常使用函数来实现对象的创建,这天然适合实现工厂模式。
简单工厂模式示例
假设我们要根据传入的类型字符串创建不同的支付方式对象:
立即学习“go语言免费学习笔记(深入)”;
type Payment interface { Pay(amount float64) string } type Alipay struct{} func (a *Alipay) Pay(amount float64) string { return fmt.Sprintf("支付宝支付 %.2f 元", amount) } type WechatPay struct{} func (w *WechatPay) Pay(amount float64) string { return fmt.Sprintf("微信支付 %.2f 元", amount) }定义一个工厂函数来创建对应的支付实例:
func NewPayment(method string) Payment { switch method { case "alipay": return &Alipay{} case "wechat": return &WechatPay{} default: return nil } }使用方式:
pay := NewPayment("alipay") if pay != nil { result := pay.Pay(99.9) fmt.Println(result) // 输出:支付宝支付 99.90 元 }这种方式结构清晰,适用于类型变化不频繁的场景。
抽象工厂模式进阶
当系统中存在多个产品族时,可以使用更复杂的抽象工厂模式。比如同时支持国内和国际支付,并提供对应的消息通知服务。
定义消息接口及实现:
type Notify interface { Send(msg string) string } type SMSNotify struct{} func (s *SMSNotify) Send(msg string) string { return "发送短信:" + msg } type EmailNotify struct{} func (e *EmailNotify) Send(msg string) string { return "发送邮件:" + msg }定义工厂接口:
type PaymentFactory interface { CreatePayment() Payment CreateNotify() Notify }实现国内工厂:
type CNFactory struct{} func (c *CNFactory) CreatePayment() Payment { return &Alipay{} } func (c *CNFactory) CreateNotify() Notify { return &SMSNotify{} }实现国际工厂:
type InternationalFactory struct{} func (i *InternationalFactory) CreatePayment() Payment { return &WechatPay{} // 假设海外用微信 } func (i *InternationalFactory) CreateNotify() Notify { return &EmailNotify{} }通过配置选择工厂:
func GetFactory(region string) PaymentFactory { switch region { case "cn": return &CNFactory{} case "intl": return &InternationalFactory{} default: return nil } }使用示例:
factory := GetFactory("cn") payment := factory.CreatePayment() notify := factory.CreateNotify() fmt.Println(payment.Pay(50)) fmt.Println(notify.Send("订单已支付"))工厂模式的优势与适用场景
使用工厂模式的主要好处包括:
- 解耦创建逻辑:调用方不需要知道具体类型,只依赖接口
- 易于扩展:新增类型只需添加实现并修改工厂逻辑,不影响已有代码
- 集中管理对象创建:便于统一处理初始化参数、日志、错误等
常见应用场景有:
- 数据库驱动选择(MySQL、PostgreSQL、SQLite)
- 缓存实现切换(Redis、Memcached)
- 配置加载方式(JSON、YAML、环境变量)
- API客户端构建(不同服务商)
基本上就这些。Go语言通过接口和结构体组合的方式,让工厂模式实现非常自然,不需要复杂语法支持也能写出清晰、可扩展的代码。










