Original类是原始类,里面有需要保存的属性value及创建一个备忘录类,用来保存value值。Memento类是备忘录类,Storage类是存储备忘录的类,持有Memento类的实例,该模式很好理解。
/**
* @author: muyichun
* @date : 2016年3月23日18:35:52
* @function: 备忘录模式
*/
public class Main{
public static void main(String[] args) {
Original origi = new Original("xu");
Storage storage = new Storage(origi.createMemento());
System.out.println("初始状态为:" + origi.getValue());
origi.setValue("jing");
System.out.println("修改后的状态:" + origi.getValue());
origi.restoreMemento(storage.getMemento());
System.out.println("恢复后的状态为:" + origi.getValue());
}
}
// 原始对象
class Original{
private String value;
public Original(String value){
this.value = value;
}
public String getValue(){
return value;
}
public void setValue(String value){
this.value = value;
}
//创建备份
public Memento createMemento(){
return new Memento(value);
}
//恢复备份
public void restoreMemento(Memento memento){
this.value = memento.getValue();
}
}
//备份对象
class Memento{
private String value;
public Memento(String value){
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
//仓库(存储所有的备份对象)
class Storage{
private Memento memento;
public Storage(Memento memento){
this.memento = memento;
}
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}——贴上自己喜欢的代码!
本文通过一个具体的Java实现案例介绍了备忘录设计模式。该模式允许在不破坏封装性的前提下捕获一个对象的内部状态,并在以后能够恢复到之前的状态。文章展示了Original类、Memento类和Storage类的作用及其交互过程。
1557

被折叠的 条评论
为什么被折叠?



