一)类图
二)Java代码
Shape代表一个图形,简单起见,在例子中,图形只有简单的(x,y)坐标信息。方法moveto的每次调用将改变shape对象的状态。在备忘录模式中,Shape相当于Originstor,需要记录某个时刻的状态,方法createMemento负责将Shape某个时刻的状态保存成一个备忘录对象,方法removeMemento从一个备忘录对象中恢复Shape的状态。对于Shape来说,它是备忘录对象的使用者,它看到备忘录对象的宽接口Memento,可以直接操控备忘录对象的内部属性,用于恢复Shape对象,代码如下:
- package testIBM;
- public class Shape {
- private int x;
- private int y;
- public Shape(int x, int y) {
- this.x = x;
- this.y = y;
- }
- public Memento createMemento() {
- return new Memento(x, y);
- }
- public void restoreMemento(Memento memento) {
- x = memento.getX();
- y = memento.getY();
- }
- public String getPosition() {
- return "(" + x + "," + y + ")";
- }
- public void moveTo(int x, int y) {
- this.x = x;
- this.y = y;
- }
- }
- package testIBM;
- public interface MementoIF {
- }
- package testIBM;
- //这个是备忘录
- public class Memento implements MementoIF {
- private int x;
- private int y;
- public Memento(int x, int y) {
- this.x=x;
- this.y=y;
- }
- public int getX() {
- return x;
- }
- public int getY() {
- return y;
- }
- }
- package testIBM;
- public class CareTaker {
- private MementoIF memento;
- public MementoIF getMemento() {
- return memento;
- }
- public void saveMemento(MementoIF memento) {
- this.memento=memento;
- }
- }
Client演示了如何使用备忘录进行状态保存和恢复。代码如下:
- package testIBM;
- public class TestIt {
- public static void main(String[] args) {
- Shape shape=new Shape(0,0);
- CareTaker careTaker=new CareTaker();
- shape.moveTo(22, 24);
- careTaker.saveMemento(shape.createMemento());
- System.out.println("保存shape状态对象。当前位置是"+shape.getPosition());
- shape.moveTo(33, 44);
- System.out.println("移到新位置"+shape.getPosition());
- shape.restoreMemento((Memento)careTaker.getMemento());
- System.out.println("恢复"+shape.getPosition());
- }
- }