Skip to content

Commit 959228f

Browse files
feat: prototype pattern added
1 parent 050ac92 commit 959228f

File tree

4 files changed

+83
-0
lines changed

4 files changed

+83
-0
lines changed

designpatterns/prototype/file.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package prototype
2+
3+
import "fmt"
4+
5+
type file struct {
6+
name string
7+
}
8+
9+
func (f *file) print(indentation string) {
10+
fmt.Println(indentation + f.name)
11+
}
12+
13+
func (f *file) clone() nodeInterface {
14+
return &file{name: f.name + "_clone"}
15+
}

designpatterns/prototype/folder.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package prototype
2+
3+
import "fmt"
4+
5+
type folder struct {
6+
children []nodeInterface
7+
name string
8+
}
9+
10+
func (f *folder) print(indentation string) {
11+
fmt.Println(indentation + f.name)
12+
for _, i := range f.children {
13+
i.print(indentation + indentation)
14+
}
15+
}
16+
17+
func (f *folder) clone() nodeInterface {
18+
cloneFolder := &folder{name: f.name + "_clone"}
19+
var tempChildren []nodeInterface
20+
for _, i := range f.children {
21+
copy := i.clone()
22+
tempChildren = append(tempChildren, copy)
23+
}
24+
cloneFolder.children = tempChildren
25+
return cloneFolder
26+
}
27+
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package prototype
2+
type nodeInterface interface {
3+
print(string)
4+
clone() nodeInterface
5+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package prototype
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
// test client code and how to use the factory
9+
func TestProtoType(t *testing.T) {
10+
t.Run("Test File And Folder Hierarchy", func(t *testing.T) {
11+
file1 := &file{name: "File1"}
12+
file2 := &file{name: "File2"}
13+
file3 := &file{name: "File3"}
14+
15+
folder1 := &folder{
16+
children: []nodeInterface{file1},
17+
name: "Folder1",
18+
}
19+
20+
folder2 := &folder{
21+
children: []nodeInterface{folder1, file2, file3},
22+
name: "Folder2",
23+
}
24+
fmt.Println("\nPrinting hierarchy for Folder2")
25+
folder2.print(" ")
26+
27+
cloneFolder := folder2.clone()
28+
fmt.Println("\nPrinting hierarchy for clone Folder")
29+
cloneFolder.print(" ")
30+
})
31+
}
32+
33+
34+
35+
36+

0 commit comments

Comments
 (0)