Design Patterns | Prototype

Creational pattern - Prototype

Use cases:

  • you need a chance to have a copy of given object without coupling on object’s dependency classes
  • your code shouldn’t depend on conrete realization of class
  • when you add some specific configuration to classes and want to supply your object with this config

Example:

1
2
3
4
5
6
7
package main

type inode interface {
print(string)
clone() inode
}

Here we define basic interface inode that have clone and print functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import "fmt"

type file struct {
name string
}

func (f *file) print(identation string) {
fmt.Printf("%s printing file %s \n", identation, f.name)
}
func (f *file) clone() inode {
return &file{name: f.name}
}

Structure filecode that implements inode interface.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import "fmt"

type folder struct {
childrens []inode
name string
}

func (f *folder) print(identation string) {
fmt.Printf("%s printing hierachy for folder %s \n", identation, f.name)
for _, v := range f.childrens {
v.print(identation + identation)
}
}

func (f *folder) clone() inode {
dir := &folder{name: f.name}
for _, v := range f.childrens {
dir.childrens = append(dir.childrens, v.clone())
}
return dir
}

Structure foldercode that implements inode interface.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

func main() {
folder1 := initFS()
folder2 := someBusinessLogic(folder1)
folder1.print(" ")
folder2.print(" ")

}
func someBusinessLogic(in inode) inode {
return in.clone()

}
func initFS() inode {
file1 := &file{name: "File1"}
file2 := &file{name: "File2"}
file3 := &file{name: "File3"}
folder1 := &folder{
childrens: []inode{file1},
name: "Folder1",
}
folder2 := &folder{
childrens: []inode{folder1, file2, file3},
name: "Folder2",
}
return folder2
}

Initialize filesystem and create identical copy.

1
2
3
4
5
6
7
8
9
10
11
go run .
printing hierachy for folder Folder2
printing hierachy for folder Folder1
printing file File1
printing file File2
printing file File3
printing hierachy for folder Folder2
printing hierachy for folder Folder1
printing file File1
printing file File2
printing file File3