clone()
原型模式的使用场景:
- 创建新对象的操作比较耗资源(如数据库操作)或代价比较高时。比较起从头创建新对象,克隆对象明显更加可取
- 要被克隆的对象创建起来比较复杂时:比如对象克隆的过程中存在深度拷贝或分层拷贝时;又比如要被克隆的对象存在无法被直接访问到的私有成员时。
原型模式的UML类图:
在日常中我们遇到的包含新建、copy这些操作的场景最多的就是常规的文件系统操作了。所以接下来会以文件系统为例介绍下原型模式。
inodeinodeclone()
inode.go
typeinode interface{ print(string) clone() inode}
filefolderinode
file.go
import"fmt"typefile struct{ name string}func(f *file) print(indentation string) { fmt.Println(indentation + f.name)}func(f *file) clone() inode { return&file{name: f.name + "_clone"}}
folder.go
import"fmt"typefolder struct{ children []inode name string}func(f *folder) print(indentation string) { fmt.Println(indentation + f.name) for_, i := rangef.children { i.print(indentation + indentation) }}func(f *folder) clone() inode { cloneFolder := &folder{name: f.name + "_clone"} vartempChildren []inode for_, i := rangef.children { copy := i.clone() tempChildren = append(tempChildren, copy) } cloneFolder.children = tempChildren returncloneFolder}
filefolderprint()clone()inodeinodeclone()
main
import( "fmt")funcmain() { file1 := &file{name: "File1"} file2 := &file{name: "File2"} file3 := &file{name: "File3"} folder1 := &folder{ children: []inode{file1}, name: "Folder1", } folder2 := &folder{ children: []inode{folder1, file2, file3}, name: "Folder2", } fmt.Println("\nPrinting hierarchy for Folder2") folder2.print(" ") cloneFolder := folder2.clone() fmt.Println("\nPrinting hierarchy for clone Folder") cloneFolder.print(" ")}
运行结果是:
Printing hierarchy forFolder2 Folder2 Folder1 File1 File2 File3Printing hierarchy forclone Folder Folder2_clone Folder1_clone File1_clone File2_clone File3_clone
代码已上传至GitHub, 地址: zhyea / go-patterns / prototype-pattern
END!