C#基础Memento备忘录模式(行为型模式).pdfVIP

  • 0
  • 0
  • 约5.87千字
  • 约 14页
  • 2022-11-13 发布于山东
  • 举报
C#基础Memento备忘录模式(行为型模式) Examda 提示:在不破坏封装性的前提下,捕获一个对象的内部状态,并在 该对象之外保存这个状态。这样以后就可以将该对象恢复到原先保存的状 态。 我们首先看看不适用设计模式来解决对象状态恢复的状况。 public class Rectangle : ICloneable { int x; int y; int width; int height; public void SetValue(Rectangle r) { this.x = r.x; this.y = r.y; this.width = r.width; this.height = r.height; } public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } public void MoveTo(Point p) { // } public void ChangeWidth(int width) { } public void ChangeHeight(int height) { } public void Draw(Graphics graphic) { } #region ICloneable 成员 public object Clone() { return this.MemberwiseClone(); } #endregio } public class GraphicsSystem { //原发器对象: //有必要对自身内部状态进展保存,然后在某个点处又需要恢复内部 状态的对象 Rectangle r = new Rectangle(0, 0, 10, 10); //备忘录对象: //保存原发器对象的内部状态,但不供应原发器对象支持的操作 Rectangle rSaved = new Rectangle(0, 0, 10, 10); public void Process() { rSaved = r.Clone(); // } public void Saved_Click(object sender, EventArgs e) { r.SetValue(rSaved); // } } class Program { static void Main(string[] args) { Rectangle r = new Rectangle(0, 0, 10, 10); GraphicsSystem g = new GraphicsSystem(); g.Process(r); } } 上面的代码中 Rectangle 类实现了 ICloneable 接口,这个接口利用 浅拷贝返回一个新的Rectangle 对象 在 GraphicsSystem 类中,我们定义了一个原发器对象 r,和备忘录对 象 rSaved,在 Process 的时候,我们将原发器对象进展克隆保存在rSaved 引用中。在 Saved_Click 方法中,将备忘录对象 rSaved 保存的值复原给 原发器对象 r。但这样来做,备忘录对象提过了原发器对象的一些操作, 那么我们现在需要将备忘录对象抽象出来。 public class Rectangle { int x; int y; int width; int height; public void SetValue(Rectangle r) { this.x = r.x; this.y = r.y; this.width = r.width; this.height = r.height

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档