工厂模式通过接口和工厂函数解耦对象创建与使用。定义Shape接口及Circle、Rectangle实现类型,Draw方法返回绘制信息;NewShape函数根据传入的字符串参数返回对应形状实例;main函数调用NewShape创建对象并调用Draw方法,输出“Drawing a circle”和“Drawing a rectangle”。该模式适用于需动态确定类型的场景,提升代码可维护性和扩展性。

在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"
}
使用函数根据输入参数返回对应的对象实例。
func NewShape(shapeType string) Shape {
switch shapeType {
case "circle":
return &Circle{}
case "rectangle":
return &Rectangle{}
default:
return nil
}
}
在主程序中调用工厂函数生成对象并使用。
立即学习“go语言免费学习笔记(深入)”;
func main() {
shape1 := NewShape("circle")
shape2 := NewShape("rectangle")
if shape1 != nil {
fmt.Println(shape1.Draw())
}
if shape2 != nil {
fmt.Println(shape2.Draw())
}
}
运行结果:
Drawing a circle
Drawing a rectangle
基本上就这些。通过接口定义行为,工厂函数按需创建具体类型,调用方无需关心内部实现,解耦清晰。这种模式适合需要动态决定对象类型的场景。
以上就是Golang工厂模式创建对象完整示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号