Design Patterns---Memento Pattern

1 Introduction

When we write documents and code, we always want to go back to a previous state. How can we achieve this? Press ctrl+z or command+z to achieve, to help us restore to a desired state. In software design, there is a design pattern corresponding to it - the Memento pattern.

2 Definitions

Without breaking encapsulation, capture the internal state of an object and save that state outside the object so that the object can be restored to the previously saved state later when needed. This mode is also called snapshot mode.

3 Structure and Implementation

The memo mode mainly includes the following three roles:

1. Originator role: record the internal state information at the current moment, provide the functions of creating memos and restoring memorandum data, and realize other business functions. It can access all the information in the memorandum.

2. Memento role: responsible for storing the internal state of the initiator, and providing these internal states to the initiator when needed.

3. Manager (caretaker) role: Manage memos, provide functions of saving and obtaining memos, but cannot access and modify the contents of memos.

The structure is shown below (from reference 2):

4 Advantages and disadvantages 

The memento pattern is an object behavioral pattern with the following main advantages:

1. Provides a mechanism by which the state can be restored. When the user needs, it is more convenient to restore the data to a certain historical state.

2. Implemented the encapsulation of the internal state. This state information is not accessible to objects other than the originator who created it.

3. Simplify the originator. Sponsors do not need to manage and keep individual backups of their internal state, all state information is kept in memos and managed by managers, which conforms to the single responsibility principle.

Its main disadvantages are:

1. Large resource consumption. If the internal state information to be saved is too much or is very frequent, it will occupy a relatively large memory resource.

5 Application scenarios

1. Scenarios that need to save and restore data, such as the archive function of intermediate results when playing games.

2. It is necessary to provide a scene that can be rolled back, such as Word, Notepad, Photoshop, Eclipse and other software press Ctrl+Z key combination when editing, as well as transaction operations in the database.

6 Code Examples

Now there are four beauties for you to choose. You can swipe left and right to view the specific information of the beauties. When you see the last beauties and want to choose the beauties in front, you can find the corresponding beauties by entering the number to the manager.

6.1 Memo BeautifulGirl

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-10-14 10:44
 **/
@Data
@AllArgsConstructor
public class BeautifulGirl {

    /**
     * 姓名
     */
    private String name;

    /**
     * 年龄
     */
    private int age;

    /**
     * 擅长的才艺
     */
    private String art;
}

6.2 Originator

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-10-14 10:49
 **/
@Data
public class Originator{

    private BeautifulGirl girl;

    public Originator(BeautifulGirl girl){
        this.girl = girl;
    }

    //存储
    public BeautifulGirl createMemento() {
        return this.getGirl();
    }

    //恢复
    public void restoreMemento(BeautifulGirl girl){
        this.setGirl(girl);
    }
}

6.3 Manager Caretaker

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-10-14 11:21
 **/
public class Caretaker {
    private final Map<Integer, BeautifulGirl> originator = new HashMap<>(16);

    public void setMemento(int seq, BeautifulGirl girl){
        this.originator.put(seq, girl);
    }

    public BeautifulGirl getMemento(int id){
        return this.originator.get(id);
    }
}

6.4 Main function

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-10-14 10:38
 **/
public class MainClass {
    public static void main(String[] args) throws CloneNotSupportedException {
        BeautifulGirl[] girls = new BeautifulGirl[]{
                new BeautifulGirl("貂蝉", 22, "跳舞"),
                new BeautifulGirl("西施", 18, "画画"),
                new BeautifulGirl("王昭君", 20, "弹琵琶"),
                new BeautifulGirl("杨玉环", 19, "唱歌")
        };

        //从第一个开始选择
        Originator originator = new Originator(girls[0]);
        Caretaker caretaker = new Caretaker();
        //存储选择的第一个
        caretaker.setMemento(1, originator.createMemento());
        //选择第二个
        originator.setGirl(girls[1]);
        //存储第二个
        caretaker.setMemento(2, originator.createMemento());
        //选择第三个
        originator.setGirl(girls[2]);
        //存储第三个
        caretaker.setMemento(3, originator.createMemento());
        //选择第四个
        originator.setGirl(girls[3]);
        //存储第四个
        caretaker.setMemento(4, originator.createMemento());

        //最后到底选择第几个了?
        originator.restoreMemento(caretaker.getMemento(3));

        System.out.println(originator.getGirl());
    }
}

6.5 Running Results

1. The state of the variable when debugging to the last line

2. The status of the completion of the operation

7 Summary

This article briefly introduces the memo design pattern. The popular understanding is to store the previous state. When we want to "regret", there are traces to follow. Through a simple code example similar to a blind date, all the girls we have seen before are stored. When we want to select a girl we have seen before, we only need to find the blind date manager, say the serial number, and then we can find the corresponding girl.

In the initiator code, we can combine the prototype mode to copy a copy of the girl's information in our hands to the manager, so we won't put the code here.

8 Quotes

1. "Dahua Design Patterns"

2. Memo mode (detailed version)

9 Source code

design-pattern-learning/src/com/hz/design/pattern/memento at main · airhonor/design-pattern-learning · GitHub

Guess you like

Origin blog.csdn.net/honor_zhang/article/details/120758668