PHP备忘录模式保存对象状态吗

wen PHP项目 2

本文目录导读:

PHP备忘录模式保存对象状态吗

  1. 核心作用
  2. 基本结构
  3. 关键特点
  4. 与普通快照的区别
  5. 典型应用场景

是的,PHP中的备忘录模式(Memento Pattern)专门用于保存和恢复对象的内部状态,而不会暴露对象的实现细节。

核心作用

备忘录模式的主要目的就是在不破坏封装性的前提下,捕获并外部化一个对象的内部状态,以便将来可以将该对象恢复到之前保存的状态。

基本结构

<?php
// 1. 发起人(Originator)- 需要保存状态的对象
class Editor {
    private $content = '';
    private $title = '';
    public function write($text) {
        $this->content .= $text;
    }
    // 创建备忘录:保存当前状态
    public function save(): Memento {
        return new Memento($this->content, $this->title);
    }
    // 从备忘录恢复状态
    public function restore(Memento $memento) {
        $this->content = $memento->getContent();
        $this->title = $memento->getTitle();
    }
    public function getContent() {
        return $this->content;
    }
    public function setTitle($title) {
        $this->title = $title;
    }
}
// 2. 备忘录(Memento)- 存储状态
class Memento {
    private $content;
    private $title;
    private $timestamp;
    public function __construct($content, $title) {
        $this->content = $content;
        $this->title = $title;
        $this->timestamp = time();
    }
    // 只对 Originator 暴露的接口
    public function getContent() {
        return $this->content;
    }
    public function getTitle() {
        return $this->title;
    }
    public function getTimestamp() {
        return $this->timestamp;
    }
}
// 3. 负责人(Caretaker)- 管理备忘录
class History {
    private $mementos = [];
    public function push(Memento $memento) {
        $this->mementos[] = $memento;
    }
    public function pop(): ?Memento {
        return array_pop($this->mementos);
    }
}
// 使用示例
$editor = new Editor();
$history = new History();
$editor->setTitle("草稿1");
$editor->write("第一行文字");
$history->push($editor->save()); // 保存状态
$editor->write("第二行文字");
$history->push($editor->save()); // 保存状态
$editor->write("第三行文字");
echo $editor->getContent(); // 输出: 第一行文字第二行文字第三行文字
// 撤销操作
$editor->restore($history->pop());
echo $editor->getContent(); // 输出: 第一行文字第二行文字
$editor->restore($history->pop());
echo $editor->getContent(); // 输出: 第一行文字
?>

关键特点

  1. 状态保存:确实保存对象的全部或部分状态
  2. 封装性保护:只有 Originator 可以访问备忘录的内部数据
  3. 恢复机制:提供 restore() 方法恢复历史状态
  4. 无限历史:可以保存多个时间点的状态快照

与普通快照的区别

特性 备忘录模式 普通对象克隆
封装性 保护内部结构 可能暴露细节
选择性保存 可选择保存部分状态 克隆整个对象
历史管理 可保存多个版本 通常只克隆当前
恢复复杂度 简单调用restore 需手动赋值

典型应用场景

  • 撤销/重做功能(文本编辑器、图像处理)
  • 事务回滚(数据库操作)
  • 游戏存档(保存玩家进度)
  • 表单数据恢复(Web应用)

所以答案是明确的:PHP备忘录模式的核心功能就是保存和恢复对象的状态,这是该设计模式存在的根本目的。

抱歉,评论功能暂时关闭!