
The Prototype pattern is a creational pattern that allows objects to be created from existing objects of the same class. This pattern is useful when creating objects is expensive or time-consuming, and you want to avoid unnecessary duplication of objects.
To implement the Prototype pattern in Golang, you can define an interface that includes a method to clone the object. Then, you can define a struct that implements this interface and provides a clone method that returns a copy of itself.
Example
Here's an example implementation of the Prototype pattern in Golang:
package main
import "fmt"
type Cloneable interface {
Clone() Cloneable
}
type Person struct {
Name string
Age int
}
func (p *Person) Clone() Cloneable {
return &Person{
Name: p.Name,
Age: p.Age,
}
}
func main() {
person1 := &Person{Name: "Alice", Age: 30}
person2 := person1.Clone().(*Person)
fmt.Println(person1)
fmt.Println(person2)
}
In this example, we define a Cloneable interface that includes a Clone method. Then, we define a Person struct that implements this interface and provides a Clone method that returns a copy of itself.
In the main function, we create a person1 object and then use the Clone method to create a copy of it (person2). We can then print both objects to confirm that person2 is a copy of person1.
Conclusion
Overall, the Prototype pattern can be a useful tool for creating objects in a more efficient and flexible way. By leveraging existing objects, you can avoid unnecessary duplication and improve the performance of your application.
References
- “Design Patterns: Elements of Reusable Object-Oriented Software” by Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm
About the author
Senior Freelancer & Technical Lead
Working as a Golang developer since 2020. Working as a mobile developer since 2013.
Focussed on architecture, testability and clean code. Open minded & product driven. Based in Rhede, available world-wide
Comments
Join the discussionHi and thanks for sharing. I think bether to return Person struct in Clone() method instead of Interface. I saw many example that return interface. would you like to describe why return Interface?
Golang Patterns
Welcome to the Golang Patterns tutorial series! In this series, we will explore the various software patterns that can be applied in Golang to create flexible, scalable, and maintainable software.




