【设计模式】第20节:行为型模式之“备忘录模式”-CSDN博客

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

一、简介

备忘录模式也叫快照模式具体来说就是在不违背封装原则的前提下捕获一个对象的内部状态并在该对象之外保存这个状态以便之后恢复对象为先前的状态。这个模式的定义表达了两部分内容一部分是存储副本以便后期恢复另一部分是要在不违背封装原则的前提下进行对象的备份和恢复。

二、优缺点

1. 优点

  • 封装性
  • 简易恢复和撤销
  • 简化发起人

2. 缺点

  • 增加内存使用
  • 性能开销
  • 复杂性

三、适用场景

  • 需要维护对象状态的历史记录
  • 不想暴露复杂内部结构

四、UML类图

请添加图片描述

五、案例

文本编辑器允许保存当前内容以及从保存的快照中恢复。

package main

import "fmt"

type Memento struct {
	content string
}

func NewMemento(content string) *Memento {
	return &Memento{content: content}
}

func (m *Memento) GetContent() string {
	return m.content
}

type TextEditor struct {
	Content string
}

func NewTextEditor() *TextEditor {
	return &TextEditor{Content: ""}
}

func (te *TextEditor) Write(text string) {
	te.Content += text
	fmt.Printf("Current content: %v\n", te.Content)
}

func (te *TextEditor) Save() *Memento {
	return NewMemento(te.Content)
}

func (te *TextEditor) Restore(memento *Memento) {
	te.Content = memento.GetContent()
}

func main() {
	editor := NewTextEditor()
	editor.Write("This is the first sentence.")
	saved := editor.Save()
	editor.Write("This is the second sentence.")
	fmt.Printf("Before restore: %v\n", editor.Save().GetContent())

	editor.Restore(saved)
	fmt.Printf("After restore: %v\n", editor.Save().GetContent())
}
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6