工厂模式通过封装对象创建逻辑,提升代码解耦与扩展性。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("订单已支付"))使用工厂模式的主要好处包括:
常见应用场景有:
基本上就这些。Go语言通过接口和结构体组合的方式,让工厂模式实现非常自然,不需要复杂语法支持也能写出清晰、可扩展的代码。
以上就是Golang Factory工厂模式创建对象实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号