How to Implement the Factory Pattern in Go

Implement the Factory Pattern in Go by defining an interface, creating concrete structs, and using a factory function to return the appropriate interface implementation.

Implement the Factory Pattern in Go by defining an interface for the product, creating concrete structs that implement it, and writing a factory function that returns the interface based on input parameters.

// Define the product interface
type Shape interface {
    Area() float64
}

// Concrete product
type Circle struct { Radius float64 }
func (c Circle) Area() float64 { return 3.14159 * c.Radius * c.Radius }

// Factory function
func NewShape(kind string, radius float64) Shape {
    switch kind {
    case "circle":
        return Circle{Radius: radius}
    default:
        return nil
    }
}