Golang - Prototype Pattern

Matthias Bruns
2 min readMar 7, 2023

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…

--

--

Matthias Bruns

Senior Freelancer & Technical Lead Working as a Golang developer since 2020. as a mobile developer since 2013. Focussed on architecture & testability.