Prototype
When to Use (Problem)
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)
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)
Expected Outcome (Consequences)
- Objects are self-duplicate capable at runtime.
- Objects facilitates evolution over time.
- Simplify duplication process.