定义
在现有类的封装已经固定的情况下,需要临时备份对象的某些状态,以便在某些业务逻辑中需要还原对象的这些状态。此时引入临时备份对象实现次效果。
类图
从上面类图中看不出彼此之间的关系,也就无法理解备忘模式了。详情还是请看代码吧,其实是十分简单的。
代码
1 /// <summary> 2 /// 订单类 3 /// </summary> 4 public class OrderInfo 5 { 6 public string Code 7 { 8 get; 9 set; 10 } 11 public string UserId 12 { 13 get; 14 set; 15 } 16 private string state = "新增"; 17 public string State 18 { 19 get; 20 set; 21 } 22 /// <summary> 23 /// 回滚订单状态 24 /// </summary> 25 /// <param name="orderBackup"></param> 26 public void RollbackState(OrderBackup orderBackup) 27 { 28 this.State = orderBackup.State; 29 } 30 /// <summary> 31 /// 建立备忘信息 32 /// </summary> 33 /// <returns></returns> 34 public OrderBackup BackUpState() 35 { 36 return new OrderBackup(this.State); 37 } 38 39 } 40 /// <summary> 41 /// 订单状态备忘类 42 /// </summary> 43 public class OrderBackup 44 { 45 public string State 46 { 47 get; 48 private set; 49 } 50 public OrderBackup(string state) 51 { 52 this.State = state; 53 } 54 } 55 /// <summary> 56 /// 订单管理类 57 /// </summary> 58 public class OrderManager 59 { 60 /// <summary> 61 /// 提交订单 62 /// </summary> 63 /// <param name="orderInfo"></param> 64 public void CommitOrder(OrderInfo orderInfo) 65 { 66 OrderBackup orderBackup = orderInfo.BackUpState(); 67 try 68 { 69 //TODO summit the order 70 orderInfo.State = "提交"; 71 } 72 catch (Exception ex) 73 { 74 //rollback 75 orderInfo.RollbackState(orderBackup); 76 throw new Exception("commit the order faile", ex); 77 } 78 } 79 } 80 /// <summary> 81 /// 客户端调用测试 82 /// </summary> 83 public class MementoClient 84 { 85 public void Test() 86 { 87 OrderInfo orderInfo = new OrderInfo() 88 { 89 Code = "empId" + DateTime.Now.ToString("yyyyMMddHHmmssfff"), 90 UserId="empId", 91 State="新增" 92 }; 93 new OrderManager().CommitOrder(orderInfo); 94 } 95 }
总结
备忘模式更多的试用于需要回滚的事务中,而且是相对复杂的业务。单个状态的备份是不需要到备忘类来备份的,当涉及到多个状态(多个字段),而且处理业务相对复杂时,才去考虑。