Skip to main content

Command Palette

Search for a command to run...

Golang - Prototype Pattern

Updated
2 min read
Golang - Prototype Pattern
M

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

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

M

Hi 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

Part 2 of 19

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.

Up next

Golang - Options vs Builder Pattern

When it comes to creating complex objects in Golang, two patterns are commonly used: the Options pattern and the Builder pattern. Both patterns have their advantages and disadvantages, and choosing the right pattern depends on the specific needs of y...

More from this blog

Matthias Bruns

69 posts