抽象工厂模式在Go中通过接口定义产品族、工厂接口统一创建逻辑来实现,支持跨平台UI组件的系列化创建与扩展。

抽象工厂模式用于创建一系列相关或相互依赖的对象,而无需指定它们的具体类。在 Go 中,由于没有传统面向对象的继承和抽象类,我们通过接口组合 + 工厂函数(或结构体方法)来实现这一模式,核心是“用接口定义产品族,用工厂接口统一创建逻辑”。
先为每个产品角色定义接口,比如一个跨平台 UI 库可能有 Button 和 Checkbox:
Button 和 Checkbox 是两个产品角色,各自在不同平台(Windows/macOS)有具体实现:
// 产品接口
type Button interface {
Render() string
}
type Checkbox interface {
Render() string
}
// 具体产品:Windows 实现
type WinButton struct{}
func (w WinButton) Render() string { return "Rendering Windows button" }
type WinCheckbox struct{}
func (w WinCheckbox) Render() string { return "Rendering Windows checkbox" }
// 具体产品:macOS 实现
type MacButton struct{}
func (m MacButton) Render() string { return "Rendering macOS button" }
type MacCheckbox struct{}
func (m MacCheckbox) Render() string { return "Rendering macOS checkbox" }
声明一个工厂接口,包含创建每类产品的方法。它不关心具体实现,只约定能力:
立即学习“go语言免费学习笔记(深入)”;
type GUIFactory interface {
CreateButton() Button
CreateCheckbox() Checkbox
}
然后为每个平台实现该接口:
// Windows 工厂
type WinFactory struct{}
func (w WinFactory) CreateButton() Button { return WinButton{} }
func (w WinFactory) CreateCheckbox() Checkbox { return WinCheckbox{} }
// macOS 工厂
type MacFactory struct{}
func (m MacFactory) CreateButton() Button { return MacButton{} }
func (m MacFactory) CreateCheckbox() Checkbox { return MacCheckbox{} }
客户端只依赖 GUIFactory 接口,运行时传入具体工厂实例即可生成整套一致的产品:
func Application(factory GUIFactory) string {
button := factory.CreateButton()
checkbox := factory.CreateCheckbox()
return button.Render() + "\n" + checkbox.Render()
}
// 使用示例
func main() {
winApp := Application(WinFactory{})
fmt.Println(winApp)
// 输出:
// Rendering Windows button
// Rendering Windows checkbox
macApp := Application(MacFactory{})
fmt.Println(macApp)
// 输出:
// Rendering macOS button
// Rendering macOS checkbox
}
以上就是如何使用Golang实现抽象工厂模式_创建多个相关对象族的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号