定義:保存一個對象的某個狀態,以便在適當的時候恢復對象
特點:
1、給用戶提供了一種可以恢復狀態的機制,可以使用戶能夠比較方便地回到某個歷史的狀態。
2、實現了信息的封裝,使得用戶不需要關心狀態的保存細節。
企業級應用和常用框架中的應用:常見文本編輯器使用了該模式
實例:
注意:該實例中只有撤銷操作,沒有向前還原操作
/** * 目標對象:將要被備忘的對象 */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; }}/** * 備忘錄對象 */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; }}/** * 負責人對象:負責記錄備忘錄對象 */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("沒有可還原的內容");  return null; } WordMemento memento = list.get(index-1); list.remove(index-1); index--; return memento; }}以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答