登录
首页 >  Golang >  Go教程

Golang工厂模式创建对象详解

时间:2025-09-25 22:36:54 468浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《Golang工厂模式创建对象教程》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

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

Golang工厂模式创建对象完整示例

在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
    }
}

使用工厂创建对象

在主程序中调用工厂函数生成对象并使用。

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工厂模式创建对象详解》的详细内容,更多关于golang,接口,工厂模式,对象创建,工厂函数的资料请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>