源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

轻松掌握Java备忘录模式

  • 时间:2020-09-24 18:12 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:轻松掌握Java备忘录模式
[b]定义:[/b]保存一个对象的某个状态,以便在适当的时候恢复对象 [b]特点:[/b]     1、给用户提供了一种可以恢复状态的机制,可以使用户能够比较方便地回到某个历史的状态。     2、实现了信息的封装,使得用户不需要关心状态的保存细节。 企业级应用和常用框架中的应用:常见文本编辑器使用了该模式 [b]实例:[/b] 注意:该实例中只有撤销操作,没有向前还原操作
/**
 * 目标对象:将要被备忘的对象
 */
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;
 }
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部