🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 概念示例 通过基于操作系统文件系统的示例来理解原型模式 ``` package main import ( "fmt" "strings" ) // 原型接口 type inode interface { print(string) string clone() inode } // 具体原型:文件 type file struct { name string } func (f *file) print(indentation string) string { return indentation + f.name + "_clone" + "\n" } func (f *file) clone() inode { return &file{name: f.name} } // 具体原型:目录 type folder struct { childrens []inode name string } func (f *folder) print(indentation string) string { builder := strings.Builder{} builder.WriteString(indentation + f.name + "\n") for _, i := range f.childrens { builder.WriteString(i.print(indentation + indentation)) } return builder.String() } func (f *folder) clone() inode { cloneFolder := &folder{name: f.name + "_clone"} var tempChildrens []inode for _, i := range f.childrens { tempChildrens = append(tempChildrens, i.clone()) } cloneFolder.childrens = tempChildrens return cloneFolder } func main() { 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", } fmt.Printf("%+v\n", folder2.print(" ")) cloneFolder := folder2.clone() fmt.Printf("%+v\n", cloneFolder.print(" ")) } ``` 输出 ``` Folder2 Folder1 File1_clone File2_clone File3_clone Folder2_clone Folder1_clone File1_clone File2_clone File3_clone ```