search
HomeBackend DevelopmentPHP Tutorial学习php设计模式 php实现备忘录模式(Memento)_PHP

一、意图
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样可以在以后把该对象的状态恢复到之前保存的状态。

二、备忘录模式结构图

三、备忘录模式中主要角色
1、备忘录(Memento)角色:
存储发起人(Originator)对象的内部状态,而发起人根据需要决定备忘录存储发起人的哪些内部状态。
备忘录可以保护其内容不被发起人(Originator)对象之外的任何对象所读取。
2、发起人(Originator)角色:
创建一个含有当前的内部状态的备忘录对象
使用备忘录对象存储其内部状态
3、负责人(Caretaker)角色:
负责保存备忘录对象,不检查备忘录对象的内容
四、备忘录模式的优点和缺点
备忘录模式的优点:
1、有时一些发起人对象的内部信息必须保存在发起人对象以外的地方,但是必须要由发起人对象自己读取。
2、简化了发起人(Originator)类。发起人(Originator)不再需要管理和保存其内部状态的一个个版本,客户端可以自行管理它们所需要的这些状态的版本
3、当发起人角色的状态改变的时候,有可能这个状态无效,这时候就可以使用暂时存储起来的备忘录将状态复原。
备忘录模式的缺点:
1、如果发起人角色的状态需要完整地存储到备忘录对象中,那么在资源消耗上面备忘录对象会很昂贵。
2、当负责人角色将一个备忘录存储起来的时候,负责人可能并不知道这个状态会占用多大的存储空间,从而无法提醒用户一个操作是否会很昂贵。
3、当发起人角色的状态改变的时候,有可能这个状态无效。
五、备忘录模式适用场景
1、必须保存一个对象在某一个时刻的(部分)状态,这样以后需要时它才能恢复到先前的状态。
2、如果一个用接口来让其它对象直接得到这些状态,将会暴露对象的实现细节并破坏对象的封装性。
六、备忘录模式与其它模式
1、命令模式(command模式):Command模式也可以用来恢复对象的状态,一般Command模式可以支持多级状态的回滚,Memento只是简单的恢复(快照)。在Command模式的每一个undo中,可以使用Memento来保存对象的状态。
2、迭代器模式(Iterator模式):备忘录可以用于迭代
七、备忘录模式PHP示例

<&#63;php
/**
 * 发起人(Originator)角色
 */
class Originator {
 
  private $_state;
 
  public function __construct() {
    $this->_state = '';
  }
 
  /**
   * 创建备忘录
   * @return Memento 包含当前状态的备忘录对象
   */
  public function createMemento() {
    return new Memento($this->_state);
  }
 
  /**
   * 将发起人恢复到备忘录对象记录的状态上
   * @param Memento $memento
   */
  public function restoreMemento(Memento $memento) {
    $this->_state = $memento->getState();
  }
 
  public function setState($state) {
    $this->_state = $state;
  }
 
  public function getState() {
    return $this->_state;
  }
 
  /**
   * 测试用方法,显示状态
   */
  public function showState() {
    echo "Original Status:", $this->getState(), "<br />";
  }
 
}
 
/**
 * 备忘录(Memento)角色
 */
class Memento {
 
  private $_state;
 
  public function __construct($state) {
    $this->setState($state);
  }
 
  public function getState() {
    return $this->_state;
  }
 
  public function setState($state) {
    $this->_state = $state;
  }
 
}
 
/**
 * 负责人(Caretaker)角色
 */
class Caretaker {
 
  private $_memento;
 
  public function getMemento() {
    return $this->_memento;
  }
 
  public function setMemento(Memento $memento) {
    $this->_memento = $memento;
  }
 
}
 
/**
 * 客户端
 */
class Client {
 
  /**
   * Main program.
   */
  public static function main() {
 
    /* 创建目标对象 */
    $org = new Originator();
    $org->setState('open');
    $org->showState();
 
    /* 创建备忘 */
    $memento = $org->createMemento();
 
    /* 通过Caretaker保存此备忘 */
    $caretaker = new Caretaker();
    $caretaker->setMemento($memento);
 
    /* 改变目标对象的状态 */
    $org->setState('close');
    $org->showState();
 
    /* 还原操作 */
    $org->restoreMemento($caretaker->getMemento());
    $org->showState();
  }
 
}
 
Client::main();
&#63;>

以上就是使用php实现备忘录模式的代码,还有一些关于备忘录模式的概念区分,希望对大家的学习有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!