Memento_Model
发起人_Originator
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Memento_Model
{
class Originator
{
private string state;
public string State
{
get { return state; }
set { state = value; }
}
public Memento CreatMemento()
{
return new Memento(state);
}
public void SetMemento(Memento memento)
{
state = memento.State;
}
public void Show()
{
Console.WriteLine("State = "+ state);
}
}
}
备忘录_Memento
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Memento_Model
{
class Memento
{
private string state;
public Memento(string state)
{
this.state = state;
}
public string State
{
get { return state; }
set { state = value; }
}
}
}
管理者
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Memento_Model
{
class Caretaker
{
private Memento memento;
public Memento Memento
{
get { return memento; }
set { memento = value; }
}
}
}
客户端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Memento_Model
{
class Program
{
static void Main(string[] args)
{
Originator o1 = new Originator();
o1.State = "On";
o1.Show();
Caretaker c = new Caretaker();
c.Memento = o1.CreatMemento();
o1.State = "Off";
o1.Show();
o1.SetMemento(c.Memento);
o1.Show();
Console.ReadKey();
}
}
}
总结:把要保存的细节封装到Memento中,那一天要更改保存的细节,就不会影响客户端了
应用:Memento模式比较适用于功能比较复杂的,但是需要维护或者记录属性历史的类,或需要保存的属性只是众多属性中的一小部分时。Originaotr可以根绝保存的Memento信息还远到前一状态。