栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

轻松掌握Java备忘录模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

轻松掌握Java备忘录模式

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

特点:

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/149053.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号