Definition : Without violating encapsulation, capture and restored to this state later.
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象态
对象状态的回溯
Originator --> Memonto (SetM,CreateM)
class Rectangle : ICloneable{ int x; int y; int width; int height; public void SetValue(Rectangle r){ } public object Clone(){ return this.MemberwieseClone(); } public Rectangle(int x, int y, int width, int height){ ... } public void MoveTo(Point p){ } public void ChangeWidth(int width){ } public void ChangeHeight(int height){ } public void Draw(Graphic graphic){ } }
class GraphicsSystem{ //原发器对象--有必要对自身状态进行保存和恢复 Rectangle r = new Rectangle(0, 0, 10, 10); //备忘录对象--保存原发器对象的状态,但不支持其操作 Rectange rSaved = new Rectangle(0, 0, 10, 10);
public void Process(Rectangle r){ rSaved = r.Clone(); }
public static Restore_Click(object sender, EventArgs e){ r.SetValue(rSaved); } }
| externalize an object's
internal state so that the object can be
之外保存这个状态。这样以后就可以将该对象恢复到原先保存的状
class Rectangle{
int x; int y;
int width; int height;
public Rectangle(int x, int y, int width, int height){ ... }
public void MoveTo(Point p){ }
public void ChangeWidth(int width){ }
public void ChangeHeight(int height){ }
public void Draw(Graphic graphic){ } public RectangleMemoto CreateMemento(){ RectangleMemoto rm = new RectangleMemoto (); rm.SetValue(....); return rm; } public void Restore(RectangleMemoto rm){ this.x = rm.x; ...... }
}
class RectangleMemoto{
internal int x; internal int y;
internal int width; internal int height;
internal void SetValue(int x, int y, int width, int height){ ... }
}
class GraphicSystem{ //原发器对象--有必要对自身状态进行保存和恢复
Rectangle r = new Rectangle(0, 0, 10, 10);
//备忘录对象--保存原发器对象的状态,但不支持其操作
RectangleMemoto rSaved = new RectangleMemoto(); public void Process(){ rSaved = r.CreateMemento(); }
public static Restore_Click(object sender, EventArgs e){
r.Restore(rSaved);
} }
|