In short, the memorandum mode supports rollback. Suppose a notepad supports the rollback operation. How can this problem be achieved?
First, a memorandum class is required.
public class Memento
{ private string _msg;
public Memento(string msg)
{ _msg = msg;
}
public string GetText()
{ return _msg;
}
}
Above,
○ The constructor is called every time nodepad records information. The information recorded by nodepad is finally assigned to the _ MSG field through this constructor.
○ The gettext method is called when the nodepad performs the rollback operation.
The next step is the nodepad class.
public class Notepad
{ private string _msg;
public Memento SetMsg(string msg)
{ Memento m = new Memento(msg);
_msg = msg;
return m;
}
public string GetMsg()
{ return _msg;
}
public void Undo(Memento previousState)
{ if (previousState != null)
{ _msg = previousState.GetText();
}
else
{ _msg = "";
}
}
}
○ Maintain a string-type field _ MSG, representing the text displayed on nodepad
○ Record information method setmsg: not only must the record information be assigned to _ MSG, but also the information be transmitted to the memorandum class.
○ Getmsg: Read _ msg
○ Rollback operation method undo: Assign the last message of the memo to _ MSG. If you roll back to the previous operation for the first time, it is equivalent to the condition in which the memorandum is null and must be considered as null.
The client needs to have a list of memos for the maintainer.
class Program
{ static void Main(string[] args)
{ IList<Memento> undos = new List<Memento>();
Notepad notepad = new Notepad();
Memento undo;
undo = notepad.SetMsg("Hello"); undos.Add(undo);
undo = notepad.SetMsg("World"); undos.Add(undo);
Console. writeline ("go to nodepad to view information "); Console.WriteLine(notepad.GetMsg());
Console. writeline ("1. Perform a rollback operation "); notepad.Undo(undos[0]);
Console. writeline ("view information after rollback "); Console.WriteLine(notepad.GetMsg());
Console. writeline ("2. Perform another rollback operation "); notepad.Undo(null);
Console. writeline ("view information after rollback "); Console.WriteLine(notepad.GetMsg());
Console.ReadKey();
}
}
○ The first time you enter notepad to view information, you will see the last entered World;
○ Roll back once. The second time you enter notepad to view the information, you will see the first hello input;
○ Roll back again. For the third time, enter notepad to view the information. An empty string is displayed.
Memento Pattern)