Definition: Save a certain state of an object so that the object can be restored at the appropriate time
Features:
1. Provide users with a mechanism to restore state, which allows users to return to a certain historical state more conveniently.
2. The information is encapsulated so that users do not need to care about the details of state preservation.
Applications in enterprise-level applications and common frameworks: Common text editors use this mode
Example:
Note: In this instance, there is only the undo operation, no forward restore operation
/** * Target object: object to be memorized*/class Word { private String content; private String image; private String table; public Word(String content, String image, String table) { super(); this.content = content; this.image = image; this.table = table; } public WordMemento memento(){ return new WordMemento(this); } public void recovery(WordMemento memento){ this.content = memento.getContent(); this.image = memento.getImage(); this.table = memento.getTable(); } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getTable() { return table; } public void setTable(String table) { this.table = table; }}/** * Memorandum object*/class WordMemento{ private String content; private String image; private String table; public WordMemento(Word word) { this.content = word.getContent(); this.image = word.getImage(); this.table = word.getTable(); } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getTable() { return table; } public void setTable(String table) { this.table = table; }}/** * Person in charge object: responsible for recording memorandum object*/class CareTaker{ private List<WordMemento> list = new ArrayList<>(); private int index = 0; public void setMemento(WordMemento memento){ list.add(memento); this.index = list.size(); } public WordMemento getWordMemento(){ if(index == 0){ System.out.println("No restoreable content"); return null; } WordMemento memento = list.get(index-1); list.remove(index-1); index--; return memento; }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.