Welcome to our comprehensive guide on the Go Factory Pattern! This tutorial is designed for both beginners and intermediate learners, so let's dive right in.
The Go Factory Pattern, also known as the Factory Pattern, is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be produced. It's a powerful tool for promoting loose coupling and improving code organization.
Let's see how the Go Factory Pattern works with a simple example.
// Abstract Product - The interface that all concrete products must implement
type Animal interface {
Speak() string
}
// Concrete Products - Concrete implementations of the Animal interface
type Dog struct{}
type Cat struct{}
// Concrete Creator - A concrete implementation of the Creator interface
type PetStore struct {
animals map[string]Animal
}
func (p *PetStore) CreateAnimal(animalType string) Animal {
if animal, ok := p.animals[animalType]; ok {
return animal
}
switch animalType {
case "dog":
p.animals[animalType] = &Dog{}
return p.animals[animalType]
case "cat":
p.animals[animalType] = &Cat{}
return p.animals[animalType]
default:
panic("Unknown animal type")
}
}
func main() {
petStore := &PetStore{
animals: map[string]Animal{},
}
dog := petStore.CreateAnimal("dog")
cat := petStore.CreateAnimal("cat")
fmt.Println(dog.Speak()) // Output: "Woof!"
fmt.Println(cat.Speak()) // Output: "Meow!"
}In this example, we have an Animal interface and two concrete implementations, Dog and Cat. We also have a PetStore, which acts as the factory. The CreateAnimal method of the PetStore is responsible for creating instances of either Dog or Cat. By using the Factory Pattern, we can easily add new animal types to our system without modifying the existing code.
What is the main purpose of the Go Factory Pattern?
That's it for our introduction to the Go Factory Pattern! Stay tuned for more in-depth examples and practical applications. Happy coding! 💡💻🚀