行为型模式-备忘录模式

using System;
using System.Text;
using System.Collections.Generic;

namespace 备忘录模式
{

/*
* 备忘录模式意图:用一个中介者对象将一些列对象交互封装,从而降低这些对象间的耦合性并且可以独立地改变对象间的交互关系
*/

///<summary>
///
///</summary>
publicclass Originator
{
privatestring state;

publicstring State
{
get { return state; }
set { state = value; }
}

///<summary>
/// 创建备忘录,将当前要保存的信息导入并实例化备忘录
///</summary>
///<returns></returns>
public Memento CreateMemento()
{
returnnew Memento(this.State);
}

///<summary>
/// 恢复备忘录,将Memento导入并将相关数据恢复
///</summary>
///<param name="memento"></param>
publicvoid SetMemento(Memento memento)
{
this.State = memento.State;
}

///<summary>
/// 展示状态数据
///</summary>
publicvoid Show()
{
//显示当前的状态
}
}
///<summary>
/// 备忘录类Memento
///</summary>
publicclass Memento
{
privatestring state;

public Memento(string state)
{
this.state = state;
}

publicstring State
{
get { return state; }
set { state = value; }
}
}
///<summary>
/// 管理者类
///</summary>
publicclass Caretaker
{
private Memento memento;

public Memento Memento
{
get { return memento; }
set { memento = value; }
}
}

publicclass AppClient
{
staticvoid Main(string[] args)
{
Originator o
=new Originator();

//初始状态为On

o.State
="On";

o.Show();



//创建备忘录并保存状态

Caretaker caretaker
=new Caretaker();
//caretaker.Memento = o.CreateMemento();

caretaker.Memento
= o.CreateMemento();



//更改Originator状态=Off

o.State
="Off";

o.Show();



//恢复到原始状态

o.SetMemento(caretaker.Memento);

o.Show();


}
}
}
posted @ 2011-03-22 22:29  日月之明  阅读(1258)  评论(3编辑  收藏  举报