主讲:李建忠
来源:http://www.microsoft.com/china/msdn/events/webcasts/shared/webcast/consyscourse/CsharpOOD.aspx
1: [Serializable]
2: public class Rectangle
3: {
4: int x;
5: int y;
6: int weight;
7: int height;
8:
9: pulic void SetValue(Rectangle r)
10: {
11: this.x=r.x;
12: this.y=r.y;
13: this.weight=r.weight;
14: this.height=r.height;
15: }
16:
17: public Rectangle(int x,int y,int weight,int height)
18: {
19: this.x=x;
20: this.y=y;
21: this.weight=weight;
22: this.height=height;
23: }
24:
25: public void MoveTo(Point p)
26: {
27:
28: }
29:
30: public void ChangeWidth(int width)
31: {
32:
33: }
34:
35: public void ChangeHeight(int height)
36: {
37:
38: }
39:
40: public void Draw(Graphic graphic)
41: {
42:
43: }
44:
45: public GeneralMemento CreateMemento()
46: {
47: GeneralMemento gm=new GeneralMemento();
48: gm.SetState(this);
49: return gm;
50: }
51:
52: public void SetMemento(GeneralMemento gm)
53: {
54: Recgletangle r=(Retangle)gm.GetState();
55:
56: this.x=r.x;
57: this.y=r.y;
58: this.weight=r.weight;
59: this.height=r.height;
60: }
61: }
62:
63: class GeneralMemento
64: {
65: Stream rSaved;
66: public GeneralMemento(Factory factory)
67: {
68: rSaved=factory.CreateStream();
69: }
70:
71: public void SetState(object r)
72: {
73: BinaryFormat bf=new BinaryFormat();
74: bf.Serializa(r,rSaved);
75: }
76:
77: internal object GetState()
78: {
79: BinaryFormat bf=new BinaryFormat();
80: rSaved.Seek(0,seek.Original);
81: object obj=bf.DeSerialize(rSaved);
82:
83: return obj;
84: }
85: }
86:
87: //处于另外的程序集中
88: class GraphicSystem
89: {
90: //原发器对象
91: //有必要对自身内部状态进行保存,然后再某个点处又需要恢复内部状态的对象
92: Rectangle r=new Rectangle(0,0,10,10);
93:
94: //备忘录对象——保存原发器对象的状态,但是不提供原发器对象支持的操作
95: //MemoryStream rSaved=new MemoryStream();
96:
97: public static void Main()
98: {
99: Process(r);
100: }
101:
102: public static void Process(Rectangle r)
103: {
104: gm=r.CreateMemento();
105:
106: //...
107: }
108: }
109:
110: public void Saved_Click(object sender,EventArgs e)
111: {
112: gm.SetMemento(r);
113: }