行为模式--备忘录模式

一)类图

二)Java代码

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

Code:
  1. packagetestIBM;
  2. publicclassShape{
  3. privateintx;
  4. privateinty;
  5. publicShape(intx,inty){
  6. this.x=x;
  7. this.y=y;
  8. }
  9. publicMementocreateMemento(){
  10. returnnewMemento(x,y);
  11. }
  12. publicvoidrestoreMemento(Mementomemento){
  13. x=memento.getX();
  14. y=memento.getY();
  15. }
  16. publicStringgetPosition(){
  17. return"("+x+","+y+")";
  18. }
  19. publicvoidmoveTo(intx,inty){
  20. this.x=x;
  21. this.y=y;
  22. }
  23. }
Code:
  1. packagetestIBM;
  2. publicinterfaceMementoIF{
  3. }
Code:
  1. packagetestIBM;
  2. //这个是备忘录
  3. publicclassMementoimplementsMementoIF{
  4. privateintx;
  5. privateinty;
  6. publicMemento(intx,inty){
  7. this.x=x;
  8. this.y=y;
  9. }
  10. publicintgetX(){
  11. returnx;
  12. }
  13. publicintgetY(){
  14. returny;
  15. }
  16. }
Code:
  1. packagetestIBM;
  2. publicclassCareTaker{
  3. privateMementoIFmemento;
  4. publicMementoIFgetMemento(){
  5. returnmemento;
  6. }
  7. publicvoidsaveMemento(MementoIFmemento){
  8. this.memento=memento;
  9. }
  10. }

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

Code:
  1. packagetestIBM;
  2. publicclassTestIt{
  3. publicstaticvoidmain(String[]args){
  4. Shapeshape=newShape(0,0);
  5. CareTakercareTaker=newCareTaker();
  6. shape.moveTo(22,24);
  7. careTaker.saveMemento(shape.createMemento());
  8. System.out.println("保存shape状态对象。当前位置是"+shape.getPosition());
  9. shape.moveTo(33,44);
  10. System.out.println("移到新位置"+shape.getPosition());
  11. shape.restoreMemento((Memento)careTaker.getMemento());
  12. System.out.println("恢复"+shape.getPosition());
  13. }
  14. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值