工厂类在 Golang 中是一种设计模式,用于创建对象的统一接口,分离创建逻辑和客户端代码。它提供以下优点:分离创建逻辑可扩展性减少代码冗余工厂类适合在需要创建不同类型对象、创建过程复杂或需要集中化对象创建时使用。

深入了解Golang中的工厂类设计

深入Golang中的工厂类设计

在Golang中,工厂类是一种设计模式,它提供了创建对象的统一接口,从而避免创建对象的具体细节。它允许我们通过提供一个创建对象的方法来分离对象创建逻辑和客户代码。

工厂类示例

让我们编写一个示例工厂类来创建不同的形状:

package main

import "fmt"

type Shape interface {
    Draw()
}

type Circle struct{}

func (c *Circle) Draw() {
    fmt.Println("Drawing a circle")
}

type Square struct{}

func (s *Square) Draw() {
    fmt.Println("Drawing a square")
}

type ShapeFactory struct{}

func (f *ShapeFactory) CreateShape(shapeType string) (Shape, error) {
    switch shapeType {
    case "circle":
        return &Circle{}, nil
    case "square":
        return &Square{}, nil
    default:
        return nil, fmt.Errorf("Invalid shape type: %s", shapeType)
    }
}

func main() {
    factory := ShapeFactory{}
    
    circle, err := factory.CreateShape("circle")
    if err != nil {
        fmt.Println(err)
        return
    }
    circle.Draw()

    square, err := factory.CreateShape("square")
    if err != nil {
        fmt.Println(err)
        return
    }
    square.Draw()
}

实战案例

在实际应用中,工厂类可以用于以下场景:

优点

何时使用工厂类?