工厂方法模式通过接口和函数解耦对象创建与使用,Go语言中定义Shape接口及Circle、Rectangle实现,再通过ShapeFactory根据类型字符串动态创建对应实例,新增类型只需扩展工厂判断分支,符合开闭原则,结合映射表可优化大量类型判断。

工厂方法模式用于解耦对象的创建与使用,特别适合需要动态创建不同类型的对象的场景。在 Go 语言中,虽然没有类和继承的概念,但通过接口和函数可以很好地实现工厂方法模式。
我们先定义一个统一的产品接口,不同的具体类型将实现这个接口。
<strong>type Shape interface {</strong>
Draw() string
<strong>}</strong>
接下来实现几个具体的结构体:
<strong>type Circle struct{}</strong>
func (c *Circle) Draw() string {
return "Drawing a circle"
}
<strong>type Rectangle struct{}</strong>
func (r *Rectangle) Draw() string {
return "Drawing a rectangle"
}
工厂函数根据输入参数返回对应的 Shape 实例。这是工厂方法的核心。
立即学习“go语言免费学习笔记(深入)”;
<strong>type ShapeFactory struct{}</strong>
func (f *ShapeFactory) CreateShape(shapeType string) Shape {
switch shapeType {
case "circle":
return &Circle{}
case "rectangle":
return &Rectangle{}
default:
panic("Unknown shape type")
}
}
下面演示如何使用工厂来动态创建对象。
func main() {
factory := &ShapeFactory{}
shapes := []string{"circle", "rectangle", "circle"}
for _, s := range shapes {
shape := factory.CreateShape(s)
fmt.Println(shape.Draw())
}
}
输出结果为:
Drawing a circle Drawing a rectangle Drawing a circle
新增形状时只需添加新结构体并实现 Shape 接口,然后在工厂函数中加入判断分支。调用代码无需修改,符合开闭原则。
如果类型较多,可结合映射表注册机制进一步优化,避免大量 switch 判断。
基本上就这些。Go 的接口和组合机制让工厂模式实现更简洁,不需要复杂的继承结构也能达到目的。
以上就是Golang工厂方法模式动态对象创建示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号