当前位置: 首页 > news >正文

【设计模式】4、prototype 原型模式

四、prototype 原型模式

https://refactoringguru.cn/design-patterns/prototype

如果希望 复制对象, 可使用 “prototype 模式”

如果 “待复制的对象” 是 interface 而不是 class, 或者如果 class 有 private 变量时. 无法知道 "待复制的对象"的细节, 则需要其实现 “clone()” 方法供外部调用.

4.1 inode

本例希望实现文件系统的复制功能. 数据结构是 inode 接口, file 和 folder 都实现了该接口. 详见 https://refactoringguru.cn/design-patterns/prototype/go/example

当然, 另一条路是: 也可以直接用序列化+反序列化实现复杂对象的 clone()

4.1.1 inode_test

package _41inodeimport "testing"func TestInode(t *testing.T) {d1 := &directory{name:     "json",children: []inode{&file{name: "a.json"}, &file{name: "b.json"}},}d2 := &directory{name:     "yaml",children: []inode{&file{"c.yaml"}, &file{"d.yaml"}},}f1 := &file{name: "e.txt"}f2 := &file{name: "f.sql"}directoryHome := directory{name:     "/home",children: []inode{d1, d2, f1, f2},}directoryHome.print(printIndent)cp := directoryHome.clone()cp.print("  ")
}// code result
=== RUN   TestInode/homejsona.jsonb.jsonyamlc.yamld.yamle.txtf.sql/home_clonejson_clonea.json_cloneb.json_cloneyaml_clonec.yaml_cloned.yaml_clonee.txt_clonef.sql_clone
--- PASS: TestInode (0.00s)
PASS

4.1.2 inode

package _41inode// inode 是文件系统的节点
type inode interface {// 打印此节点的信息, indent 是缩进符(如\t)print(indent string)// 复制此节点clone() inode
}const printIndent = "  "

4.1.3 file

package _41inodeimport "fmt"type file struct {// 文件名name string
}func (f *file) print(indent string) {str := indent + f.namefmt.Println(str)
}func (f *file) clone() inode {return &file{name: f.name + "_clone"}
}

4.1.4 directory

package _41inodeimport ("fmt"
)type directory struct {// 目录名name string// 子节点children []inode
}func (d *directory) print(indent string) {fmt.Println(indent + d.name)for _, child := range d.children {child.print(indent + printIndent) // 在基础 indent 的基础上, 再添加 printIndent}
}func (d *directory) clone() inode {children := make([]inode, 0)for _, child := range d.children {children = append(children, child.clone())}cp := &directory{name:     d.name + "_clone",children: children,}return cp
}

http://www.lryc.cn/news/338844.html

相关文章:

  • ES6 关于Class类的继承 extends(2024-04-10)
  • 边缘计算【智能+安全检测】系列教程--使用OpenCV+GStreamer实现真正的硬解码,完全消除马赛克
  • Anaconda在Ubuntu下的安装与简单使用
  • 网络编程【InetAddress , TCP 、UDP 、HTTP 案例】
  • 软考中级工程师网络技术第二节网络体系结构
  • Mac 软件清单
  • 【Leetcode每日一题】 分治 - 颜色分类(难度⭐⭐)(57)
  • 微信登录功能-保姆级教学
  • 嵌入式MCU BootLoader开发配置详细笔记教程
  • Unity 中消息提醒框
  • 好数(蓝桥杯)
  • 自动化收集Unity版本更新日志
  • 【CSS】CSS水平居中方案
  • SQL注入sqli_labs靶场第二题
  • 基于机器学习的人脸发型推荐算法研究与应用实现
  • 【服务器部署篇】Linux下Nginx的安装和配置
  • React搭建一个文章后台管理系统
  • Elasticsearch 支持的插件 —— 筑梦之路
  • HTML:链接
  • vscode远程连接centos
  • scala---面向对象(类,对象,继承,抽象类,特质)
  • 【机器学习300问】68、随机初始化神经网络权重的好处?
  • 数据结构与算法——20.B-树
  • Tomcat源码解析——Tomcat的启动流程
  • 蓝桥杯真题演练:2023B组c/c++
  • 微信小程序实现预约生成二维码
  • 专业140+总分410+北京理工大学826信号处理导论考研经验北理工电子信息通信工程,真题,参考书,大纲。
  • 做一个后台项目的架构
  • 嵌入式单片机 TTL电平、232电平、485电平的区别和联系
  • 2024年大唐杯备考