Golang - Prototype Pattern

Golang - Prototype Pattern

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

Did you find this article valuable?

Support Matthias Bruns by becoming a sponsor. Any amount is appreciated!