Skip to main content

Command Palette

Search for a command to run...

Golang - Prototype Pattern

Updated
2 min read
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

Golang Patterns

Part 18 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 - Singleton Pattern

In software engineering, the Singleton pattern is a software design pattern that restricts the instantiation of a type to one object. This is useful when exactly one object is needed to coordinate actions across the system. In this article, we will d...