Prototype

Prototype is a design pattern where an object/class is capable of cloning itself by providing a clone function, just a like a cell in biology experiencing mitosis multiplication. The class/structure itself serves as prototype for cloning. The diagram is as follows:

When to Use (Problem)

  • The problem involving complex class/structure definition and is hard to perform self-duplication at runtime.
  • The problem requires isolated self-duplication.

Example (Solution)

Here is an example of prototype design in Go:

package main

import (
        "fmt"
)

type Prototype struct {
        name string
        id   int
}

func (p *Prototype) Name() string {
        return p.name
}

func (p *Prototype) ID() int {
        return p.id
}

func (p *Prototype) Clone() *Prototype {
        return &Prototype{
                name: p.name,
                id:   p.id,
        }
}

func main() {
        creator := &Prototype{name: "James", id: 124432}
        fmt.Printf("Creator: %v\n", creator.Name())
        fmt.Printf("Creator ID: %v\n", creator.ID())

        clone1 := creator.Clone()
        fmt.Printf("Clone 1: %v\n", clone1.Name())
        fmt.Printf("Clone 1 ID: %v\n", clone1.ID())

        clone2 := creator.Clone()
        fmt.Printf("Clone 2: %v\n", clone2.Name())
        fmt.Printf("Clone 2 ID: %v\n", clone2.ID())
}

Notice that Prototype structure itself has the ability to Clone itself at a given time? Each clones are individual object which can be altered again based on their lifetime, and is clone capable again.

Expected Outcome (Consequences)

  • Objects are self-duplicate capable at runtime.
  • Objects facilitates evolution over time.
  • Simplify duplication process.