Click “like” to see, form a habit, the public account search [dime technology] pay attention to more original technical articles. This article has been included in GitHub org_Hejianhui /JavaStudy.
preface
- 23 design modes for shorthand
- The singleton pattern
- Factory Method pattern
- Abstract Factory pattern
- The Builder/Builder pattern
- Prototype mode
- Flyweight mode
- The facade pattern
- Adapter mode
- Decorator pattern
- Observer mode
- Strategy mode
- Bridge mode
- The Template Method pattern
- The Chain of Responsibility model
- Composite mode
- Proxy mode
- Updates continue at……
Here are 23 design patterns to memorize quicklyMemo modeRelated content.
The schema definition
To capture the internal state of an object without breaking encapsulation and store the state outside of the object so that the object can be restored to its original saved state later when needed. This mode is also called snapshot mode.
The template implementation is as follows:
package com.niuh.designpattern.memento.v1;
/** ** * Memo mode *
*/
public class MementoPattern {
public static void main(String[] args) {
Originator or = new Originator();
Caretaker cr = new Caretaker();
or.setState("S0");
System.out.println("Initial state :" + or.getState());
cr.setMemento(or.createMemento()); // Save the state
or.setState("S1");
System.out.println("New state :" + or.getState());
or.restoreMemento(cr.getMemento()); // Restore the status
System.out.println("Restore state :"+ or.getState()); }}/ / memo
class Memento {
private String state;
public Memento(String state) {
this.state = state;
}
public void setState(String state) {
this.state = state;
}
public String getState(a) {
returnstate; }}/ / the originator
class Originator {
private String state;
public void setState(String state) {
this.state = state;
}
public String getState(a) {
return state;
}
public Memento createMemento(a) {
return new Memento(state);
}
public void restoreMemento(Memento m) {
this.setState(m.getState()); }}/ / manager
class Caretaker {
private Memento memento;
public void setMemento(Memento m) {
memento = m;
}
public Memento getMemento(a) {
returnmemento; }}Copy the code
The following output is displayed:
Initial status :S0 New status :S1 Recovery status :S0Copy the code
Problem solved
The memo mode records the internal state of an object, and when the user regrets it can undo the current operation and restore the data to its original state.
We all make mistakes sometimes, and we all hope that there is some kind of “regret medicine” that can make up for our mistakes and let us start over, but the reality is cruel. In computer applications, customers also often make mistakes, can provide “regret medicine” to them? Of course it can, and it is necessary. This function is implemented by “memo mode”.
Patterns of
The core of the memo pattern is the design memo class and the manager class for managing the memo.
To compose (a role). | role |
---|---|
Originator role | It records the internal status information at the current time, provides the function of creating a memo and restoring the memo data, and realizes other service functions. It can access all the information in the memo. |
The Memento role | Responsible for storing the internal state of the initiator and providing this internal state to the initiator when required. |
Caretaker role | Manage memos and save and obtain memos, but cannot access or modify the contents of memos. |
Example is given to illustrate
Instance profiles
Take the game save as an example, how to use the memo mode to achieve
Using the step
Step 1: Define memo roles to store role status.
class RoleStateMemento {
private int vit; / / life
private int atk; / / damage
private int def; / / defense force
public RoleStateMemento(int vit, int atk, int def) {
this.vit = vit;
this.atk = atk;
this.def = def;
}
public int getVit(a) {
return vit;
}
public void setVit(int vit) {
this.vit = vit;
}
public int getAtk(a) {
return atk;
}
public void setAtk(int atk) {
this.atk = atk;
}
public int getDef(a) {
return def;
}
public void setDef(int def) {
this.def = def; }}Copy the code
Step 2: Define the initiator role (current game character), and record the vitality, attack and defense of the current game character. The saveState() method is used to save the current status, and the recoveryState() method is used to restore the role status.
class GameRole {
private int vit; / / life
private int atk; / / damage
private int def; / / defense force
public int getVit(a) {
return vit;
}
public void setVit(int vit) {
this.vit = vit;
}
public int getAtk(a) {
return atk;
}
public void setAtk(int atk) {
this.atk = atk;
}
public int getDef(a) {
return def;
}
public void setDef(int def) {
this.def = def;
}
// Status display
public void stateDisplay(a) {
System.out.println("Current role status:");
System.out.println("Strength:" + this.vit);
System.out.println("Attack power:" + this.atk);
System.out.println("Defense:" + this.def);
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
}
// Get the initial state
public void getInitState(a) {
this.vit = 100;
this.atk = 100;
this.def = 100;
}
/ / after the battle
public void fight(a) {
this.vit = 0;
this.atk = 0;
this.def = 0;
}
// Save the role status
public RoleStateMemento saveState(a) {
return (new RoleStateMemento(vit, atk, def));
}
// Restore the role status
public void recoveryState(RoleStateMemento memento) {
this.vit = memento.getVit();
this.atk = memento.getAtk();
this.def = memento.getDef(); }}Copy the code
Step 3: Define manager roles, role state managers
class RoleStateCaretaker {
private RoleStateMemento memento;
public RoleStateMemento getMemento(a) {
return memento;
}
public void setMemento(RoleStateMemento memento) {
this.memento = memento; }}Copy the code
Step 4: Test the output
public class MementoPattern {
// The logic is roughly saved before the boss fight, and the boss fight failed
public static void main(String[] args) {
/ / before the boss
GameRole gameRole = new GameRole();
gameRole.getInitState();
gameRole.stateDisplay();
// Save the progress
RoleStateCaretaker caretaker = new RoleStateCaretaker();
caretaker.setMemento(gameRole.saveState());
// Fail to fight boss
gameRole.fight();
gameRole.stateDisplay();
// Restore the statusgameRole.recoveryState(caretaker.getMemento()); gameRole.stateDisplay(); }}Copy the code
The output
Current Status of character: Physical Strength:100Damage:100Defense:100----------------- Current status: Physical strength:0Damage:0Defense:0----------------- Current status: Physical strength:100Damage:100Defense:100
-----------------
Copy the code
advantages
The memo pattern is an object behavior pattern with the following major advantages.
- Provides a mechanism by which states can be restored. Data can be easily restored to a historical state when the user needs it.
- Internal state encapsulation is realized. No object other than the originator that created it has access to this state information.
- Simplified initiation for humans. The sponsor does not need to manage and keep individual copies of its internal state, all state information is kept in memos and managed by the manager, in line with the principle of single responsibility.
disadvantages
High resource consumption. If the internal state information to be saved is too much or too frequent, it will occupy a large amount of memory resources.
Matters needing attention
- To comply with Demeter’s rule, you need a class that manages memos
- Do not use the memo pattern in scenarios where backups are frequently created. To save memory, use prototype mode + memo mode
Application scenarios
- Scenarios in which data needs to be saved and restored
- Provide a rollback action, such as CTRL + Z, browser Backspace button, Backspace key, etc
- Duplicate scenarios that need to be monitored
Schema extension
In memo mode, there are examples of single-state backups and examples of multi-state backups. It can be mixed with prototype patterns. In the memo mode, the “memo” is defined to back up the information of the “sponsor”, while the clone() method of the prototype mode has a self-backup function. Therefore, if the sponsor implements Cloneable interface, it can back up its own function, and then delete the memo class, its structure is as follows:
Application in source code
#Spring
org.springframework.binding.message.StateManageableMessageContext
Copy the code
StateManageableMessageContext part source
public interface StateManageableMessageContext extends MessageContext {
/**
* Create a serializable memento, or token representing a snapshot of the internal state of this message context.
* @return the messages memento
*/
public Serializable createMessagesMemento(a);
/**
* Set the state of this context from the memento provided. After this call, the messages in this context will match
* what is encapsulated inside the memento. Any previous state will be overridden.
* @param messagesMemento the messages memento
*/
public void restoreMessages(Serializable messagesMemento);
/**
* Configure the message source used to resolve messages added to this context. May be set at any time to change how
* coded messages are resolved.
* @param messageSource the message source
* @see MessageContext#addMessage(MessageResolver)
*/
public void setMessageSource(MessageSource messageSource);
}
Copy the code
PS: The above code is submitted to Github: github.com/Niuh-Study/…
GitHub Org_Hejianhui /JavaStudy GitHub Hejianhui /JavaStudy