Original: Curly brace MC(wechat official account: Huakuohao-MC), welcome to share, please keep the source.
The memo mode is used to back up part of an object’s internal state and, if needed, restore the object’s state to its original state.
For example
Let’s say you’re playing a game everyday and you want your character to save his state before he fights a big boss, and if he fails to fight a big boss, you want him to return to his original state so you can start again. At this point we can consider using the memo mode.
Take a look at the UML diagram:
Take a look at the code implementation
Start by creating a memo to record the states that need to be recorded.
public class Memento {
// Multiple states need to be saved
private String state;
public Memento(String state){
this.state = state;
}
public String getState(a){
returnstate; }}Copy the code
Define a game character, create a memo within that character, and save the corresponding state to the memo.
public class GameRole {
// Game state
private String state;
public String getState(a) {
return state;
}
public void setState(String state) {
this.state = state;
}
// Save the status to the memo
public Memento saveStateToMemento(a){
return new Memento(state);
}
// Get the status from the memo
public void getStateFromMemento(Memento memento){ state = memento.getState(); }}Copy the code
Defines an administrative class for storing and restoring state in memos.
public class CareTaker {
// Back up multiple states
private List<Memento> mementoList = new ArrayList<Memento>();
public void add(Memento memento){
mementoList.add(memento);
}
public Memento get(int index){
returnmementoList.get(index); }}Copy the code
The client is used this way
public class MementoPatternDemo {
public static void main(String[] args){
GameRole gameRole = new GameRole();
CareTaker careTaker = new CareTaker();
gameRole.setState("State #1");
gameRole.setState("State #2");
careTaker.add(gameRole.saveStateToMemento());
gameRole.setState("State #3");
careTaker.add(gameRole.saveStateToMemento());
gameRole.setState("State #4");
System.out.println("Current State: " + gameRole.getState());
gameRole.getStateFromMemento(careTaker.get(0));
System.out.println("First saved State: " + gameRole.getState());
gameRole.getStateFromMemento(careTaker.get(1));
System.out.println("Second saved State: "+ gameRole.getState()); }}Copy the code
conclusion
The memo pattern is one of the behavior patterns and is suitable for classes with complex functions that need to maintain or record property history, or for a small subset of many properties. It is also a design pattern with high frequency of daily use.
This paper reference www.tutorialspoint.com/design_patt…