To implement the factory design pattern in Go, you can create a factory function that returns an object that implements a common interface. This function can take parameters to specify the type of object to be created. Here is an example of how you might implement the factory design pattern in Go:
// Define an interface that the factory will create objects for
type Animal interface {
Speak() string
}
// Define a factory function that returns an object that implements the Animal interface
func NewAnimal(animalType string) Animal {
switch animalType {
case "dog":
return &Dog{}
case "cat":
return &Cat{}
default:
return nil
}
}
// Define a struct for a dog that implements the Animal interface
type Dog struct{}
func (d *Dog) Speak() string {
return "Woof!"
}
// Define a struct for a cat that implements the Animal interface
type Cat struct{}
func (c *Cat) Speak() string {
return "Meow!"
}
// Use the factory function to create new Animal objects
dog := NewAnimal("dog")
cat := NewAnimal("cat")
fmt.Println(dog.Speak()) // "Woof!"
fmt.Println(cat.Speak()) // "Meow!"
In this example, the NewAnimal() function is the factory function that returns objects of different types (Dog or Cat in this case) that implement the Animal interface. The factory function takes a string parameter that specifies the type of object to be created. The Dog and Cat structs both implement the Animal interface by implementing the Speak() method. The NewAnimal() function uses a switch statement to determine which type of object to return based on the animalType parameter.
This implementation of the factory design pattern allows you to easily create new objects of different types without having to specify the exact type of each object. It also promotes loose coupling between the different types of objects, as they only need to implement a common interface.