现在的位置: 首页 > 综合 > 正文

行为模式–备忘录模式

2014年02月02日 ⁄ 综合 ⁄ 共 2068字 ⁄ 字号 评论关闭

一)类图

 

二)Java代码

   Shape代表一个图形,简单起见,在例子中,图形只有简单的(x,y)坐标信息。方法moveto的每次调用将改变shape对象的状态。在备忘录模式中,Shape相当于Originstor,需要记录某个时刻的状态,方法createMemento负责将Shape某个时刻的状态保存成一个备忘录对象,方法removeMemento从一个备忘录对象中恢复Shape的状态。对于Shape来说,它是备忘录对象的使用者,它看到备忘录对象的宽接口Memento,可以直接操控备忘录对象的内部属性,用于恢复Shape对象,代码如下:

Code:
  1. package testIBM;  
  2.   
  3. public class Shape {  
  4.     private int x;  
  5.     private int y;  
  6.   
  7.     public Shape(int x, int y) {  
  8.         this.x = x;  
  9.         this.y = y;  
  10.     }  
  11.   
  12.     public Memento createMemento() {  
  13.         return new Memento(x, y);  
  14.     }  
  15.   
  16.     public void restoreMemento(Memento memento) {  
  17.         x = memento.getX();  
  18.         y = memento.getY();  
  19.     }  
  20.   
  21.     public String getPosition() {  
  22.         return "(" + x + "," + y + ")";  
  23.     }  
  24.   
  25.     public void moveTo(int x, int y) {  
  26.         this.x = x;  
  27.         this.y = y;  
  28.     }  
  29. }  
Code:
  1. package testIBM;  
  2.   
  3. public interface MementoIF {  
  4. }  
Code:
  1. package testIBM;  
  2.   
  3.   
  4. //这个是备忘录  
  5. public class Memento implements MementoIF {  
  6.     private int x;  
  7.     private int y;  
  8.     public Memento(int x, int y) {  
  9.        this.x=x;  
  10.        this.y=y;  
  11.     }  
  12.       
  13.     public int getX() {  
  14.        return x;  
  15.     }  
  16.       
  17.     public int getY() {  
  18.       return y;  
  19.     }  
  20. }  
Code:
  1. package testIBM;  
  2. public class CareTaker {  
  3.     private MementoIF memento;  
  4.     public MementoIF getMemento() {  
  5.        return memento;  
  6.     }  
  7.       
  8.     public void saveMemento(MementoIF memento) {  
  9.        this.memento=memento;  
  10.     }  
  11. }  

Client演示了如何使用备忘录进行状态保存和恢复。代码如下:

Code:
  1. package testIBM;  
  2.   
  3. public class TestIt {  
  4.   
  5.     public static void main(String[] args) {  
  6.         Shape shape=new Shape(0,0);  
  7.         CareTaker careTaker=new CareTaker();  
  8.           
  9.         shape.moveTo(2224);  
  10.         careTaker.saveMemento(shape.createMemento());  
  11.           
  12.         System.out.println("保存shape状态对象。当前位置是"+shape.getPosition());  
  13.           
  14.         shape.moveTo(3344);  
  15.         System.out.println("移到新位置"+shape.getPosition());  
  16.           
  17.         shape.restoreMemento((Memento)careTaker.getMemento());  
  18.         System.out.println("恢复"+shape.getPosition());  
  19.     }  
  20.   
  21. }  

 

抱歉!评论已关闭.