今天学习备忘录模式,备忘录模式很简单,我们举个例子来说,大家都在电脑上玩过象棋,象棋有个“悔棋”的功能,想必大家都用过,那这个悔棋就可以看做是一个备忘录模式。
在学习备忘录模式之前,先搞明白三个概念:
1、发起人(Originator),其实这个概念我说不太清楚,说白了,谁需要备份,谁就是发起人。拿悔棋的例子来讲,象棋就是一个发起人。
2、备忘录(Memento),将发起人的具体状态存储到这个对象中。
3、负责人(Caretaker),就是操作备忘录具体如何存储。
要注意,备忘录在客户端是透明的,客户不需要知道备忘录如何存储,只需要调用即可。
我们来看一个例子:
先看包结构:
我们按照上边的概念,依次写出对应的类,代码内有注释
package com.memento.originator;
import com.memento.memento.Memento;
/**
* 发起人
* 它可以类比为一个象棋,比如我让兵向前一步。
* 那么如果我想悔棋,我就必须要把兵向前一步之前的状态存起来
* 假设兵之前的坐标是(5,4),那么现在坐标就是(5,5)
* @author ZHENGWEI
* @date Aug 3, 2015
*/
public class Originator {
private String chessPosition;
public String getChessPosition() {
return chessPosition;
}
public void setChessPosition(String chessPosition) {
this.chessPosition = chessPosition;
}
public Memento createMemento(){
return new Memento(chessPosition);
}
/**
* 将备忘录中记录的状态恢复到当前对象中
* @param memento
*/
public void restoreMemento(Memento memento){
this.chessPosition = memento.getChessPosition();
}
}
备忘录
package com.memento.memento;
/**
* 备忘录类
* 存储棋子的具体位置
* @author ZHENGWEI
* @date Aug 3, 2015
*/
public class Memento {
private String chessPosition;
public Memento(String chessPosition) {
super();
this.chessPosition = chessPosition;
}
public String getChessPosition() {
return chessPosition;
}
public void setChessPosition(String chessPosition) {
this.chessPosition = chessPosition;
}
}
操作类:
package com.memento.caretaker;
import com.memento.memento.Memento;
public class Caretaker {
private Memento memento;
/**
* 备忘录的取值方法
*/
public Memento retrieveMemento(){
return this.memento;
}
/**
* 备忘录的赋值方法
*/
public void saveMemento(Memento memento){
this.memento = memento;
}
}
测试类
package com.memento.main;
import com.memento.caretaker.Caretaker;
import com.memento.originator.Originator;
public class MementoMain {
public static void main(String[] args) {
Originator o = new Originator();
Caretaker c = new Caretaker();
//改变负责人对象的状态
o.setChessPosition("兵(5,4)");
System.out.println("当前的状态是:"+o.getChessPosition());
//创建备忘录对象,并将发起人对象的状态储存起来
System.out.println("创建备忘录,备份状态");
c.saveMemento(o.createMemento());
//修改发起人的状态
System.out.println("改变状态");
o.setChessPosition("兵(5,5)");
System.out.println("当前的状态是:"+o.getChessPosition());
//恢复发起人对象的状态
System.out.println("现在恢复之前的状态");
o.restoreMemento(c.retrieveMemento());
System.out.println("当前的状态是:"+o.getChessPosition());
}
}
最后结果是
这就是一个简单的备忘录实现,在我目前在一些项目中用的不多,不过这都是相对的,比如上边这个象棋的例子,就可以用到这个模式