Golang設(shè)計模式之原型模式詳細(xì)講解
原型模式
原型是一種創(chuàng)建型設(shè)計模式, 使你能夠復(fù)制對象, 甚至是復(fù)雜對象, 而又無需使代碼依賴它們所屬的類。
所有的原型類都必須有一個通用的接口, 使得即使在對象所屬的具體類未知的情況下也能復(fù)制對象。 原型對象可以生成自身的完整副本, 因為相同類的對象可以相互訪問對方的私有成員變量。

概念示例
讓我們嘗試通過基于操作系統(tǒng)文件系統(tǒng)的示例來理解原型模式。 操作系統(tǒng)的文件系統(tǒng)是遞歸的: 文件夾中包含文件和文件夾, 其中又包含文件和文件夾, 以此類推。
每個文件和文件夾都可用一個 inode接口來表示。 inode接口中同樣也有 clone克隆功能。
file文件和 folder文件夾結(jié)構(gòu)體都實現(xiàn)了 print打印和 clone方法, 因為它們都是 inode類型。 同時, 注意 file和 folder中的 clone方法。 這兩者的 clone方法都會返回相應(yīng)文件或文件夾的副本。 同時在克隆過程中, 我們會在其名稱后面添加 “_clone” 字樣。
inode.go: 原型接口
package main
type Inode interface {
print(string)
clone() Inode
}
file.go: 具體原型
package main
import "fmt"
type File 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: 具體原型
package main
import "fmt"
type Folder struct {
children []Inode
name string
}
func (f *Folder) print(indentation string) {
fmt.Println(indentation + f.name)
for _, i := range f.children {
i.print(indentation + indentation)
}
}
func (f *Folder) clone() Inode {
cloneFolder := &Folder{name: f.name + "_clone"}
var tempChildren []Inode
for _, i := range f.children {
copy := i.clone()
tempChildren = append(tempChildren, copy)
}
cloneFolder.children = tempChildren
return cloneFolder
}
main.go: 客戶端代碼
package main
import "fmt"
func main() {
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(" ")
}
output.txt: 執(zhí)行結(jié)果
Printing hierarchy for Folder2
Folder2
Folder1
File1
File2
File3Printing hierarchy for clone Folder
Folder2_clone
Folder1_clone
File1_clone
File2_clone
File3_clone
到此這篇關(guān)于Golang設(shè)計模式之原型模式詳細(xì)講解的文章就介紹到這了,更多相關(guān)Go原型模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Golang實現(xiàn)讀取excel文件并轉(zhuǎn)換為JSON格式
本文介紹了如何使用Golang讀取Excel文件并將其轉(zhuǎn)換為JSON格式,通過安裝excelize依賴和創(chuàng)建readExcelToJSON方法,可以實現(xiàn)這一功能,如果需要轉(zhuǎn)換數(shù)據(jù)類型,可以修改相應(yīng)的代碼,需要的朋友可以參考下2025-03-03
golang解析網(wǎng)頁利器goquery的使用方法
這篇文章主要給大家介紹了關(guān)于golang解析網(wǎng)頁利器goquery的使用方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考借鑒,下面來一起學(xué)習(xí)學(xué)習(xí)吧。2017-09-09
Go語言如何實現(xiàn)Benchmark函數(shù)
go想要在main函數(shù)中測試benchmark會麻煩一些,所以這篇文章主要為大家介紹了如何實現(xiàn)了一個簡單的且沒有開銷的benchmark函數(shù),希望對大家有所幫助2024-12-12
Golang中interface{}轉(zhuǎn)為數(shù)組的操作
這篇文章主要介紹了Golang中interface{}轉(zhuǎn)為數(shù)組的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04
Go語言Http?Server框架實現(xiàn)一個簡單的httpServer
這篇文章主要為大家介紹了Go語言Http?Server框架實現(xiàn)一個簡單的httpServer抽象,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04

