一)类图
二)Java代码
Shape代表一个图形,简单起见,在例子中,图形只有简单的(x,y)坐标信息。方法moveto的每次调用将改变shape对象的状态。在备忘录模式中,Shape相当于Originstor,需要记录某个时刻的状态,方法createMemento负责将Shape某个时刻的状态保存成一个备忘录对象,方法removeMemento从一个备忘录对象中恢复Shape的状态。对于Shape来说,它是备忘录对象的使用者,它看到备忘录对象的宽接口Memento,可以直接操控备忘录对象的内部属性,用于恢复Shape对象,代码如下:
- packagetestIBM;
- publicclassShape{
- privateintx;
- privateinty;
- publicShape(intx,inty){
- this.x=x;
- this.y=y;
- }
- publicMementocreateMemento(){
- returnnewMemento(x,y);
- }
- publicvoidrestoreMemento(Mementomemento){
- x=memento.getX();
- y=memento.getY();
- }
- publicStringgetPosition(){
- return"("+x+","+y+")";
- }
- publicvoidmoveTo(intx,inty){
- this.x=x;
- this.y=y;
- }
- }
- packagetestIBM;
- publicinterfaceMementoIF{
- }
- packagetestIBM;
- //这个是备忘录
- publicclassMementoimplementsMementoIF{
- privateintx;
- privateinty;
- publicMemento(intx,inty){
- this.x=x;
- this.y=y;
- }
- publicintgetX(){
- returnx;
- }
- publicintgetY(){
- returny;
- }
- }
- packagetestIBM;
- publicclassCareTaker{
- privateMementoIFmemento;
- publicMementoIFgetMemento(){
- returnmemento;
- }
- publicvoidsaveMemento(MementoIFmemento){
- this.memento=memento;
- }
- }
Client演示了如何使用备忘录进行状态保存和恢复。代码如下:
- packagetestIBM;
- publicclassTestIt{
- publicstaticvoidmain(String[]args){
- Shapeshape=newShape(0,0);
- CareTakercareTaker=newCareTaker();
- 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());
- }
- }