结构 | |
意图 | 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。 |
适用性 |
|
1 using System; 2 3 class Originator 4 { 5 private double manufacturer=0; 6 private double distributor = 0; 7 private double retailer = 0; 8 9 public void MakeSale(double purchasePrice) 10 { 11 // We assume sales are divided equally amount the three 12 manufacturer += purchasePrice * .40; 13 distributor += purchasePrice *.3; 14 retailer += purchasePrice *.3; 15 // Note: to avoid rounding errors for real money handling 16 // apps, we should be using decimal integers 17 // (but hey, this is just a demo!) 18 } 19 20 public Memento CreateMemento() 21 { 22 return (new Memento(manufacturer, distributor, retailer)); 23 } 24 25 public void SetMemento(Memento m) 26 { 27 manufacturer = m.A; 28 distributor = m.B; 29 retailer = m.C; 30 } 31 } 32 33 class Memento 34 { 35 private double iA; 36 private double iB; 37 private double iC; 38 39 public Memento(double a, double b, double c) 40 { 41 iA = a; 42 iB = b; 43 iC = c; 44 } 45 46 public double A 47 { 48 get 49 { 50 return iA; 51 } 52 } 53 54 public double B 55 { 56 get 57 { 58 return iB; 59 } 60 } 61 62 public double C 63 { 64 get 65 { 66 return iC; 67 } 68 } 69 } 70 71 class caretaker 72 { 73 74 } 75 76 /// <summary> 77 /// Summary description for Client. 78 /// </summary> 79 public class Client 80 { 81 public static int Main(string[] args) 82 { 83 Originator o = new Originator(); 84 85 // Assume that during the course of running an application 86 // we we set various data in the originator 87 o.MakeSale(45.0); 88 o.MakeSale(60.0); 89 90 // Now we wish to record the state of the object 91 Memento m = o.CreateMemento(); 92 93 // We make further changes to the object 94 o.MakeSale(60.0); 95 o.MakeSale(10.0); 96 o.MakeSale(320.0); 97 98 // Then we decide ot change our minds, and revert to the saved state (and lose the changes since then) 99 o.SetMemento(m); 100 101 return 0; 102 } 103 }
备忘录模式
时间: 2024-11-04 16:11:30