首页 > 编程 > Java > 正文

轻松掌握Java备忘录模式

2019-11-26 13:47:08
字体:
来源:转载
供稿:网友

定义:保存一个对象的某个状态,以便在适当的时候恢复对象

特点:

    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; }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表