设计模式(22)---备忘录模式
基本定义
备忘录模式:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可以将该对象恢复到原先保存的状态。
解释:简单来说,就是保存一个对象在某一时刻的特定状态,在以后需要的时候可以将对象恢复到保存时的状态。
基本代码:
class Originator { private string state; public string State { get { return state; } set { state = value; } } public Memento CreateMemento() { return new Memento(state); } public void SetMemento(Memento memento) { state = memento.State; } public void Display() { Console.WriteLine("State=" + state); } } class Memento { private string state; public string State { get { return state; } } public Memento(string state) { this.state = state; } } class Caretaker { private Memento memento1; public Memento Memento1 { get { return memento1; } set { memento1 = value; } } }
客户端调用:
Originator originator = new Originator(); originator.State = "on"; originator.Display(); Caretaker caretaker = new Caretaker(); caretaker.Memento1 = originator.CreateMemento(); originator.State = "off"; originator.Display(); originator.SetMemento(caretaker.Memento1); originator.Display();
列举具体实例:
打游戏,保存一角色在打boss前的状态,待打boss结束后再恢复到它之前的状态。
class Program { static void Main(string[] args) { Role role = new Role(100, 100); Console.WriteLine("大战前:"); role.Display(); Caretaker caretaker = new Caretaker(); caretaker.memento = role.SaveMemento(); role.SetBloodFlow(20); role.SetMagicPoint(20); Console.WriteLine("大战"); role.Display(); role.RestoreMemento(caretaker.GetMemento()); Console.WriteLine("恢复"); role.Display(); Console.Read(); } } class Role { private int bloodFlow; private int magicPoint; public Role(int bloodFlow, int magicPoint) { this.bloodFlow = bloodFlow; this.magicPoint = magicPoint; } public int GetBloodFlow() { return bloodFlow; } public void SetBloodFlow(int bloodFlow) { this.bloodFlow = bloodFlow; } public int GetMagicPoint() { return magicPoint; } public void SetMagicPoint(int magicPoint) { this.magicPoint = magicPoint; } public void Display() { Console.WriteLine("用户当前的状态:"); Console.WriteLine("血量:" + GetBloodFlow() + ";蓝量:" + GetMagicPoint()); } public Memento SaveMemento() { return new Memento(GetBloodFlow (),GetMagicPoint ()); } public void RestoreMemento(Memento memento) { this.bloodFlow = memento.GetBloodFlow(); this.magicPoint = memento.GetMagicPoint(); } } class Memento { private int bloodFlow; private int magicPoint; public Memento(int bloodFlow, int magicPoint) { this.bloodFlow = bloodFlow; this.magicPoint = magicPoint; } public int GetBloodFlow() { return bloodFlow; } public void SetBloodFlow(int bloodFlow) { this.bloodFlow = bloodFlow; } public int GetMagicPoint() { return magicPoint; } public void SetMagicPoint(int magicPoint) { this.magicPoint = magicPoint; } } class Caretaker { public Memento memento; public Memento GetMemento() { return memento; } public void SetMemento(Memento memento) { this.memento = memento; } }
备忘录模式的优缺点及适用场景:
优点:
为用户提供一种可以恢复状态的机制,用户比较方便的恢复到某个历史状态。
隐藏恢复细节,用户不需要关心状态的保存细节。
缺点:
对象状态需要完整存储到备忘录对象中,如果状态数据很大,那么在资源消耗上,备忘录对象会非常耗内存。
适用场景:
简单来说,显现其优点回避其缺点的地方都可以使用备忘录模式。
最新博客信息,请关注“小项目笔记”公众号;