How to implement the factory design pattern in GoLang?
In Go language, you can use functions, methods, or structures to implement the factory design pattern.
- Implementing the factory pattern using functions: Create a function that, based on the input parameters, constructs and returns the corresponding object instance.
type Product interface {
Produce()
}
type ConcreteProductA struct {}
func (p *ConcreteProductA) Produce() {
fmt.Println("Producing Concrete Product A.")
}
type ConcreteProductB struct {}
func (p *ConcreteProductB) Produce() {
fmt.Println("Producing Concrete Product B.")
}
func CreateProduct(productType string) Product {
switch productType {
case "A":
return &ConcreteProductA{}
case "B":
return &ConcreteProductB{}
default:
return nil
}
}
- Implementing factory pattern using methods: Create a factory struct that includes a method for generating object instances.
type Product interface {
Produce()
}
type ConcreteProductA struct {}
func (p *ConcreteProductA) Produce() {
fmt.Println("Producing Concrete Product A.")
}
type ConcreteProductB struct {}
func (p *ConcreteProductB) Produce() {
fmt.Println("Producing Concrete Product B.")
}
type ProductFactory struct{}
func (f *ProductFactory) CreateProduct(productType string) Product {
switch productType {
case "A":
return &ConcreteProductA{}
case "B":
return &ConcreteProductB{}
default:
return nil
}
}
Example of use:
func main() {
product := CreateProduct("A")
product.Produce()
factory := &ProductFactory{}
product = factory.CreateProduct("B")
product.Produce()
}
These are two common methods for implementing the Factory design pattern in Go language, you can choose one based on your specific requirements.