android设计模式二十三式(十九)——备忘录模式(Memento)

编程入门 行业动态 更新时间:2024-10-09 04:16:25

android设计<a href=https://www.elefans.com/category/jswz/34/1771241.html style=模式二十三式(十九)——备忘录模式(Memento)"/>

android设计模式二十三式(十九)——备忘录模式(Memento)

备忘录模式

备忘录模式,办公人员几乎每天都会用到,不论我们在编辑什么类型的文档,还是编程,聊天,玩游戏,都在无时不刻的在使用它。

那么,还是举一个简单的栗子,我们都在编辑文档的时候,使用过Ctrl+Z来撤销我们输入的错误内容,那么为什么当我们按下Ctrl+Z的时候,能将文本返回到上一个状态呢,这还是因为有个备忘录在记录每个时刻的状态,当你按下Ctrl+Z的时候,就将某一时刻备份的数据恢复出来。

我们还是来用代码实现一下

原始类Editor是实时文本数据,Memento是备忘录,从来保存某个时刻Editor的数据,还有一个Storage用来存储管理备忘录Memento对象,但是仓库中只能存入和取出,不能修改内容,Memento按照规定,也不能修改内部保存的内容。

Editor类

/*** @author: hx* @Time: 2019/5/23* @Description: Editor*/
public class Editor {/*** 编辑的文本内容*/private String content;public String getContent() {return content;}public void setContent(String content) {this.content = content;}/*** 创建一个备忘录* @return*/public Memento createMemento(){return new Memento(content);}/*** 回复一个备忘录的数据* @param memento*/public void restoreMemento(Memento memento){content = memento.getContent();}
}

Memento类

/*** @author: hx* @Time: 2019/5/23* @Description: Memento*/
public class Memento {private String content;public Memento(String content) {this.content = content;}public String getContent() {return content;}
}

Storage类

/*** @author: hx* @Time: 2019/5/23* @Description: Storage*/
public class Storage {/*** 存储备忘录的集合*/private LinkedList<Memento> mMementos;public Storage() {mMementos = new LinkedList<>();}/*** 保存一个备忘录* @param memento*/public void addMemento(Memento memento){mMementos.addFirst(memento);}public Memento revert(){Memento memento = mMementos.getFirst();mMementos.removeFirst();return memento;}
}

 然后实际操作一下

public static void main(String[] args){Storage storage = new Storage();Editor editor = new Editor();editor.setContent("123456789");storage.addMemento(editor.createMemento());System.out.println("第一次内容:"+editor.getContent());editor.setContent("132456789qwe");storage.addMemento(editor.createMemento());System.out.println("第二次内容:"+editor.getContent());editor.setContent("132456789qwe!@#$%^");System.out.println("第三次内容:"+editor.getContent());//撤销操作editor.restoreMemento(storage.revert());System.out.println("第一次撤销:"+editor.getContent());editor.restoreMemento(storage.revert());System.out.println("第二次撤销:"+editor.getContent());
}输出结果:
第一次内容:123456789
第二次内容:132456789qwe
第三次内容:132456789qwe!@#$%^
第一次撤销:132456789qwe
第二次撤销:123456789

这里需要特别注意的是,当保存的对象不是基本数据类型的时候,保存的是数据的引用,所以如果是备份一个对象,需要重新创建一个对象并对对象赋值,或者将要保存的对象实现cloneabe接口。

细心的同学可能已经发现了,这个和原型模式非常像,只不过原型模式是保存的所有数据,实现了cloneable接口而备忘录模式,可以只对部分数据进行保存。

 

更多推荐

android设计模式二十三式(十九)——备忘录模式(Memento)

本文发布于:2024-02-06 07:06:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1747062.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模式   备忘录   二十三   android   Memento

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!