【C#设计模式(19)——备忘录模式(MementoPattern)】
前言
备忘录模式:将想要备份的信息交给备忘录对象来管理。通过设置初始、备份、修改、恢复等状态展示备忘录模式的使用。
代码
//备忘录类
public class Memento
{
private string state;
public string State { get=>state;}
public Memento(string state)
{
this.state = state;
}
}
//发起者类
public class Originator
{
private string state;
public string State { get => state; set => state = value; }
public Memento CreateMemento()
{
return new Memento(state);
}
public void RestoreMemento(Memento memento)
{
this.state = memento.State;
}
}
//管理者类
public class CareTaker
{
private Memento memento;
public Memento Memento { get => memento; set => memento = value; }
}
/*
* 行为型模式:Behavioral Pattern
* 备忘录模式:Memento Pattern
*/
internal class Program
{
static void Main(string[] args)
{
Originator originator = new Originator();
CareTaker taker = new CareTaker();
//设置初始状态
originator.State = "init state";
Console.WriteLine($"初始状态:{originator.State}");
//保存
taker.Memento = originator.CreateMemento();
//修改
originator.State = "update state";
Console.WriteLine($"修改状态:{originator.State}");
//恢复
originator.RestoreMemento(taker.Memento);
Console.WriteLine($"恢复状态:{originator.State}");
Console.ReadLine();
}
}
运行结果
原文地址:https://blog.csdn.net/weixin_43626218/article/details/144345977
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!