原理:Mem(信息类,负责封装需要保存的信息),Origin(发起者,也就是当前状态),Care(管理类,负责将Mem暂存)。需要保存时,Origin类new一个Mem,保存当前状态,发送给Care。回档时将Care赋值给Origin。
参考代码:(4条消息) Unity3D 设计模式学习之备忘录模式_unity 备忘录模式 游戏存档_liaoshengg的博客-CSDN博客
暂存游戏进度:
public class Originator{
string m_State; //状态,需要被保存
public void SetInfo(string State){
m_State = State;
}
public void ShowInfo(){
Debug.Log("Originator State"+m_State);
}
//产生要存储的记录
public Memento CreateMemento(){
Memeto newMemento = new Memento();
newMemento.SetState(m_State);
return newMemento;
}
//设置要恢复的记录
public void SetMemento(Memento m){
m_State = m.GetState();
}
}
public class Memento{
string m_State;
public string GetState(){
return m_State;
}
public void SetState(string State){
m_State = State;
}
}
public class Caretaker{
Dictionary<string,Memento> m_Mementos = new Dictionary<string,Memento>();
//增加
public void AddMemento(string Version,Memento theMemento){
if(m_Mementos.ContainsKey(Version) == false)
m_Menmentos.Add(Version,theMemento);
else{
m_Mementos[Version] = theMemento;
}
}
//读取
public Memento GetMemento(string Version){
if(m_Nementos.CointainsKey(Version)) == false){
return null;
}
return m_Mementos[Version];
}
}
void UnitTest(){
Originator theOriginator = new Originator();
CareteKer theCaretaker = new Caretaker();
//设置信息
theOriginator.SetInfo("Version1");
theOriginator.ShowInfo();
//保存
theCaretaker.AddMemento("1",theOriginator.CreateMemento());
//设置信息
theOriginator.SetInfo("Version2");
theOriginator.ShowInfo();
//保存
theCaretaker.AddMemento("2",theOriginator.CreateMemento());
//设置信息
theOriginator.SetInfo("Version3");
theOriginator.ShowInfo();
//保存
theCaretaker.AddMemento("3",theOriginator.CreateMemento());
///退回到第2版
theOriginator.SetMementor(theCaretaker.GetMemento("2"));
theOriginator.ShowInfo();
//退回到第1版
theOriginator.SetMemento(theCaretaker.GetMemento("1"));
theOriginator.ShowInfo();
}