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

工厂方法模式用于解耦对象的创建与使用,特别适合需要动态创建不同类型的对象的场景。在 Go 语言中,虽然没有类和继承的概念,但通过接口和函数可以很好地实现工厂方法模式。
定义产品接口
我们先定义一个统一的产品接口,不同的具体类型将实现这个接口。
type Shape interface {
Draw() string
}
接下来实现几个具体的结构体:
type Circle struct{}
func (c *Circle) Draw() string {
return "Drawing a circle"
}
type Rectangle struct{}
func (r *Rectangle) Draw() string {
return "Drawing a rectangle"
}
定义工厂函数
工厂函数根据输入参数返回对应的 Shape 实例。这是工厂方法的核心。
立即学习“go语言免费学习笔记(深入)”;
type ShapeFactory struct{}
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 的接口和组合机制让工厂模式实现更简洁,不需要复杂的继承结构也能达到目的。










