Golang学习笔记_45——备忘录模式

打印 上一主题 下一主题

主题 975|帖子 975|积分 2925

Golang学习笔记_42——迭代器模式
Golang学习笔记_43——责任链模式
Golang学习笔记_44——下令模式


  

一、核心概念

1. 界说

备忘录模式是一种行为型计划模式,通过在不粉碎对象封装性的前提下捕获和存储对象内部状态,实现状态的可追溯恢复机制。其核心特点包括:
状态封装:将对象状态隔离在专用备忘录对象中
汗青回溯:支持任意时间点的状态版本恢复
权限隔离:状态存储与恢复操纵限定在特定对象间
2. 办理的题目

状态不可逆:缺乏标准化的撤销/恢复机制
数据袒露风险:直接访问对象内部状态粉碎封装性
版本管理复杂:多版本状态存储与检索困难
3. 核心脚色

脚色作用Originator创建并管理备忘录的生命周期,维护内部状态Memento存储Originator内部状态的安全容器Caretaker备忘录的存储管理者,维护汗青状态记录栈 4. 类图


  1. @startuml
  2. class Originator {
  3.     - state: string
  4.     + CreateMemento(): Memento
  5.     + Restore(m: Memento)
  6. }
  7. class Memento {
  8.     - state: string
  9.     + GetState(): string
  10.     + SetState(s: string)
  11. }
  12. class Caretaker {
  13.     - history: []Memento
  14.     + Save(m: Memento)
  15.     + Retrieve(index int): Memento
  16. }
  17. Originator --> Memento
  18. Caretaker --> Memento
  19. note right of Originator::CreateMemento
  20.     创建包含当前状态的备忘录
  21.     仅Originator可访问完整数据
  22. end note
  23. @enduml
复制代码
二、特点分析

优点

  • 封装保护:严格限定状态访问权限
  • 简化恢复:标准化状态回滚操纵流程
  • 版本控制:支持多时间点状态快照管理
缺点

  • 内存消耗:大对象频繁快照导致资源占用
  • 性能消耗:深拷贝复杂对象时效率降落
  • 版本冲突:多版本管理可能引发状态不一致
三、适用场景

1. 文档编辑器

  1. type EditorMemento struct {
  2.     content string
  3. }
  4. type TextEditor struct {
  5.     content string
  6. }
  7. func (e *TextEditor) Save() *EditorMemento {
  8.     return &EditorMemento{content: e.content}
  9. }
  10. func (e *TextEditor) Restore(m *EditorMemento) {
  11.     e.content = m.content
  12. }
复制代码
2. 游戏存档系统

  1. type GameSave struct {
  2.     level   int
  3.     weapons []string
  4. }
  5. type PlayerState struct {
  6.     current *GameSave
  7. }
  8. func (p *PlayerState) QuickSave() *GameSave {
  9.     return &GameSave{
  10.         level:   p.current.level,
  11.         weapons: append([]string{}, p.current.weapons...),
  12.     }
  13. }
复制代码
3. 配置管理系统

  1. type ConfigSnapshot struct {
  2.     version string
  3.     config  map[string]interface{}
  4. }
  5. func RollbackConfig(snapshots []*ConfigSnapshot, targetVer string) error {
  6.     // 实现版本检索与配置回滚
  7. }
复制代码
四、Go语言实现示例


完整实现代码
  1. package memento_demo
  2. import "fmt"
  3. // Memento 备忘录
  4. type EditorMemento struct {
  5.         content string
  6. }
  7. func (m *EditorMemento) Content() string {
  8.         return m.content
  9. }
  10. // Originator 原发器
  11. type TextEditor struct {
  12.         content string
  13. }
  14. func (e *TextEditor) Write(input string) {
  15.         e.content += input
  16. }
  17. func (e *TextEditor) Save() *EditorMemento {
  18.         return &EditorMemento{content: e.content}
  19. }
  20. func (e *TextEditor) Restore(m *EditorMemento) {
  21.         e.content = m.Content()
  22. }
  23. // Caretaker 管理者
  24. type HistoryKeeper struct {
  25.         saves []*EditorMemento
  26. }
  27. func (h *HistoryKeeper) Push(m *EditorMemento) {
  28.         h.saves = append(h.saves, m)
  29. }
  30. func (h *HistoryKeeper) Pop() *EditorMemento {
  31.         if len(h.saves) == 0 {
  32.                 return nil
  33.         }
  34.         last := h.saves[len(h.saves)-1]
  35.         h.saves = h.saves[:len(h.saves)-1]
  36.         return last
  37. }
  38. // 客户端使用示例
  39. func ExampleUsage() {
  40.         editor := &TextEditor{}
  41.         history := &HistoryKeeper{}
  42.         // 编辑操作
  43.         editor.Write("Hello")
  44.         history.Push(editor.Save())
  45.         editor.Write(" World")
  46.         fmt.Println("Current:", editor.content)
  47.         // 撤销操作
  48.         if m := history.Pop(); m != nil {
  49.                 editor.Restore(m)
  50.         }
  51.         fmt.Println("After Undo:", editor.content)
  52. }
复制代码
执行结果
  1. === RUN   TestExampleUsage
  2. Current: Hello World
  3. After Undo: Hello
  4. --- PASS: TestExampleUsage (0.00s)
  5. PASS
复制代码
五、高级应用

1. 增量快照系统

  1. type DeltaMemento struct {
  2.     timestamp time.Time
  3.     delta     []byte
  4. }
  5. func CreateDeltaSnapshot(prev, current *DocumentState) *DeltaMemento {
  6.     // 计算差异生成增量快照
  7. }
复制代码
2. 分布式状态同步

  1. type StateSyncService struct {
  2.     snapshots map[string]*NodeState
  3. }
  4. func (s *StateSyncService) RollbackCluster(targetVer int) {
  5.     // 集群级状态回滚实现
  6. }
复制代码
六、与其他模式对比

模式核心区别典型应用场景下令模式操纵封装 vs 状态存储事务回滚系统原型模式对象克隆 vs 状态保存复杂对象复制状态模式状态转移 vs 状态存档工作流引擎 七、实现建议


  • 状态序列化:使用JSON/gob实现快照长期化
    1. func (m *Memento) Serialize() ([]byte, error) {
    2.     return json.Marshal(m)
    3. }
    复制代码
  • 内存优化:采用写时复制技能减少内存占用
  • 版本压缩:定期归并汗青快照减少存储量
  • 访问控制:严格限定Memento的字段可见性
八、典型应用


  • IDE开发环境:代码修改汗青追溯
  • 区块链系统:区块状态回滚机制
  • 机器学习:模型练习检查点
  • CI/CD管道:摆设失败快速回退
通过备忘录模式,可以构建具备完善汗青管理本领的系统架构。在Go语言中,建议:


  • 使用布局体嵌套实现宽接口/窄接口
  • 结合channel实现异步快照存储
  • 使用sync.Pool优化频繁创建的备忘录对象

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

风雨同行

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表