春季促销
原型

Go 原型模式讲解和代码示例

原型是一种创建型设计模式 使你能够复制对象 甚至是复杂对象 而又无需使代码依赖它们所属的类

所有的原型类都必须有一个通用的接口 使得即使在对象所属的具体类未知的情况下也能复制对象 原型对象可以生成自身的完整副本 因为相同类的对象可以相互访问对方的私有成员变量

概念示例

让我们尝试通过基于操作系统文件系统的示例来理解原型模式 操作系统的文件系统是递归的 文件夹中包含文件和文件夹 其中又包含文件和文件夹 以此类推

每个文件和文件夹都可用一个 inode接口来表示 inode接口中同样也有 clone克隆功能

file文件 folder文件夹结构体都实现了 print打印 clone方法 因为它们都是 inode类型 同时 注意 file folder中的 clone方法 这两者的 clone方法都会返回相应文件或文件夹的副本 同时在克隆过程中 我们会在其名称后面添加 _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: 执行结果

Printing hierarchy for Folder2
  Folder2
    Folder1
        File1
    File2
    File3

Printing hierarchy for clone Folder
  Folder2_clone
    Folder1_clone
        File1_clone
    File2_clone
    File3_clone

原型在其他编程语言中的实现

C# 原型模式讲解和代码示例 C++ 原型模式讲解和代码示例 Java 原型模式讲解和代码示例 PHP 原型模式讲解和代码示例 Python 原型模式讲解和代码示例 Ruby 原型模式讲解和代码示例 Rust 原型模式讲解和代码示例 Swift 原型模式讲解和代码示例 TypeScript 原型模式讲解和代码示例