轻松掌握Java备忘录模式_Java教程-查字典教程网
轻松掌握Java备忘录模式
轻松掌握Java备忘录模式
发布时间:2016-12-28 来源:查字典编辑
摘要:定义:保存一个对象的某个状态,以便在适当的时候恢复对象特点:1、给用户提供了一种可以恢复状态的机制,可以使用户能够比较方便地回到某个历史的状...

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

特点:

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

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

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新Java学习
    热门Java学习
    编程开发子分类