Home Java javaTutorial Detailed explanation of the memo pattern and its implementation in Java design pattern programming

Detailed explanation of the memo pattern and its implementation in Java design pattern programming

Jan 19, 2017 pm 03:37 PM

1. Definition
Capture the internal state of an object and save this state outside the object without destroying encapsulation. This allows you to later restore the object to its original saved state.

2. Reason for use
Want to restore the original state of the object at a certain time.

3. Examples of applicable situations
There are many applications of memo mode, but we have seen them before, but did not think carefully about the use of memo mode. Here are a few examples:
eg1. The use of memo in jsp+javabean:
When adding an account in a system, you need to fill in the user name, password, contact number, address and other information in the form. If some fields are not filled in or filled in incorrectly, when the user clicks " When clicking the "Submit" button, the options entered by the user need to be saved on the new page and the wrong options will be prompted. This is achieved by using the scope="request" or scope="session" characteristics of JavaBean, that is, using the memo mode.
eg2. When repairing the car's brakes. First remove the baffles on both sides to expose the left and right brake pads. Only one piece can be removed, then the other piece serves as a reminder of how the brakes are installed. After the repair of this piece is completed, the other piece can be removed. When the second piece comes off, the first piece becomes a memo.
eg3. It is said that there is no regret medicine to buy in life. We are all paying the price for what we have done, but in the soft world there is "regret medicine". After I change some state of something, as long as we have done it before After saving a certain state of the thing, we can restore the state of the thing through the memo mode. In fact, this is not a "moonlight treasure box" that can turn back time. It is always "magical".

4. Class diagram structure and description
(1) The class diagram is as follows:

Detailed explanation of the memo pattern and its implementation in Java design pattern programming

##(2) Class description    

(i ) Memento: Memento role, mainly responsible for the following tasks:
Store the internal state of the initiator object;
can protect its content from being read by any object other than the initiator (Originator) object.
(ii) Originator: The initiator role mainly completes the following tasks:
Create a memo object containing the current internal state;
Use the memo object to store its internal state.
(iii) Caretaker: Responsible person role, completes the work as follows:
is responsible for saving the memo object;
does not save the contents of the memo object.

5. Example

/**
 * 数据对象
 */
public class DataState {
  private String action;
  
  public void setAction(String action) {
    this.action = action;
  }
    
  public String getAction() {
    return action;
  }
Copy after login
/**
 * 一个保存另外一个对象内部状态拷贝 的对象.这样以后就可以将该对象恢复到原先保存的状态.
 */
import java.io.File;
import java.io.Serializable;
  
public class Memento implements Serializable {
  
  /*private int number;
  private File file = null;
  
  public Memento(Originator o) {
    this.number = o.getNumber();
    this.file = o.getFile();
  }
  
  public int getNumber() {
    return this.number;
  }
  
  public void setNumber(int number) {
    this.number = number;
  }
  
  public File getFile() {
    return this.file;
  }
  
  public void setFile(File file) {
    this.file = file;
  }
*/
  private DataState state;
  public Memento(Originator o) {
    this.state = o.getState();
  }
    
  public DataState getState() {
    return state;
  }
    
  public void setState(DataState state) {
    this.state = state;
  }
}
Copy after login


public class Originator {
  
/* private int number;
  private File file = null;
  
  public Originator() {
  
  }
  
  // 创建一个Memento,将自身作为参数传入
  public Memento getMemento() {
    return new Memento(this);
  }
  
  // 从Memento中取出保存的数据,恢复为原始状态
  public void setMemento(Memento m) {
    number = m.getNumber();
    file = m.getFile();
  }
  
  public int getNumber() {
    return number;
  }
  
  public void setNumber(int number) {
    this.number = number;
  }
  
  public File getFile() {
    return file;
  }
  
  public void setFile(File file) {
    this.file = file;
  }*/
    
  private DataState state;
  public Originator() {
      
  }
    
  public Originator(DataState state) {
    this.state = state;
  }
    
  // 创建一个Memento,将自身作为参数传入
  public Memento getMemento() {
    return new Memento(this);
  }
    
  // 从Memento中取出保存的数据,恢复为原始状态
  public void setMemento(Memento m) {
    /*
     * getMemento() 创建的对象,保存在某个容器里,
     * 当需要恢复时,将其传入当前方法, 再使用getState(),得出
     */
    this.state = m.getState();
  }
    
  public DataState getState() {
    return state;
  }
    
  public void setState(DataState state) {
    this.state = state;
  }
}
Copy after login
/*
 * Originator用于 加载数据, 建立Memento对象,及通过Memento恢复原始数据
 */
public class Test {
  public static void main(String[] args) {
      
//   Originator originator = new Originator();
//   originator.setNumber(8);
//   
//   Memento memento = originator.getMemento();
//   System.out.println(memento.getNumber());
      
    DataState state = new DataState();
    state.setAction("copy a character");
    Originator originator = new Originator();
    System.out.println("创建原始数据");
    originator.setState(state);
      
    System.out.println("创建备忘录对象, 保存原始数据状态");
    Memento memento = originator.getMemento();
      
    System.out.println("创建了一个新数据");
    originator.setState(new DataState());
  
    System.out.println("创建新数据后:" + originator.getState().getAction());
      
    /*
     * memento 需要保存在某地,需要时取出,以恢复它内部所保存的数据
     */
    System.out.println("创建新数据后,恢复原数据");
    originator.setMemento(memento);
    System.out.println(originator.getState().getAction());
  }
}
Copy after login

Print:

创建原始数据
创建备忘录对象, 保存原始数据状态
创建了一个新数据
创建新数据后:null
创建新数据后,恢复原数据
copy a character
Copy after login

More details For articles related to the memo pattern and its implementation in Java design pattern programming, please pay attention to the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles