Home > Java > javaTutorial > Introduction to Java Design Pattern Memento Pattern

Introduction to Java Design Pattern Memento Pattern

高洛峰
Release: 2017-01-19 15:44:33
Original
1311 people have browsed it

Memento definition: memento is an object that saves a copy of the internal state of another object, so that the object can be restored to its originally saved state in the future.

The Memento mode is relatively easy to understand. Let’s look at the following code:

public class Originator {
   private int number;
  private File file = null;
  public Originator(){}
  // 创建一个Memento
  public Memento getMemento(){
    return new Memento(this);
  }
  // 恢复到原始值
  public void setMemento(Memento m){
     number = m.number;
     file = m.file;
  }
}
Copy after login

Let’s look at the Memento class again:

private class Memento implements java.io.Serializable{
  private int number;
  private File file = null;
  public Memento( Originator o){
    number = o.number;
    file = o.file;
  }
}
Copy after login

It can be seen that Memento saves the number and number in Originator. The value of file. If the number and file values ​​​​in the Originator are changed, they can be restored by calling the setMemento() method.

The disadvantage of Memento mode is that it is very expensive. If there are many internal states, saving another copy will unintentionally waste a lot of memory.

Application of Memento pattern in Jsp+Javabean

In Jsp applications, we usually have many forms that require user input, such as user registration, where you need to enter your name and email, etc. If some table items The user has not filled in or filled in incorrectly. We hope that after the user presses "Submit", through the Jsp program check, if it is found that there are indeed unfilled items, a warning or error will be displayed in red under the item, and at the same time, it will also display what the user has just entered. table entry.

In the picture below, the First Name has been entered by the user, but the Last Name has not been entered. We will prompt a red text warning

Introduction to Java Design Pattern Memento Pattern

The implementation of this technology is to use The scope="request" or scope="session" characteristics of Javabeans are the Memento pattern.

For more articles related to the introduction of Memento mode (Memento mode) in Java design patterns, please pay attention to the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template