- 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
您可能关注的文档
- 2022年资产评估师《机电设备评估》第五章预习(2).pdf
- 2022年资产评估师《经济法》备考:企业与公司法律制度(2).pdf
- 2022年资产评估师《经济法》基础:财务比率分析.pdf
- 2022年自考教育心理学笔记第二章.pdf
- 2022年自考教育心理学名词解释(3).pdf
- 2022年自考写作(一)简答题总结(6).pdf
- 2022年综合辅导:水电安装工程施工方案(5).pdf
- 2022申论热点:走生态文明发展之路.pdf
- 2022投资师:建设项目管理的基本概念.pdf
- 2022物流师考试试题-配送管理理论知识.pdf
- 河北盐山中学等校2025-2026学年上学期高三一模化学试卷(含解析).docx
- 河北正定中学2025-2026学年高一上学期期末考试物理试卷(含解析).docx
- 河北张家口市怀安县2025-2026学年第一学期期末教学综合评价八年级地理试卷(含解析).docx
- 河南安阳市殷都区2025-2026学年第一学期期末教学质量检测七年级地理试卷(含解析).docx
- 河南安阳市滑县2025一2026学年第一学期期末学业质量监测八年级地理试题(含解析).docx
- 河南安阳市林州市2025-2026学年上学期期末考试高一政治试题(含解析).docx
- 河南焦作市武陟县第一中学2025-2026学年高一上学期1月月考语文试卷(含解析).docx
- 河南济源市2025-2026学年上学期期末学业质量调研七年级历史试卷(含解析).docx
- PICC导管并发症的紧急处理与护理.pptx
- 河南鹤壁市2025-2026学年高二上学期期末考试生物试题(含解析).docx
原创力文档

文档评论(0)