Motivation : Capture the internal state of an object without compromising encapsulation, and save the state outside the object. In this way, the object can be restored to the previously saved state.
Scenario: The Graphic System is used as an example. The circle is the primary machine. The system processes the circle and stores the recoverable sequence.
Structure chart
Code
Namespace Designpattern. Memento
{
/**/ /// <Summary>
///Primary machine
/// </Summary>
Public Class Round
{
Private Point centerpoint;
Private Int Radius;
Public Round (point centerpoint, Int Radius)
{
This. Centerpoint=Centerpoint;
This. Radius=Radius;
}
Public Roundmemento creatememento ()
{
Roundmemento memento= NewRoundmemento ();
Memento. setstate (This. Centerpoint,This. Radius );
ReturnMemento;
}
Public Void Setmemento (roundmemento memento)
{
This. Centerpoint=Memento. centerpoint;
This. Radius=Memento. radius;
}
Public Void Move (point)
{
}
Public Void Setlength ( Int Radius)
{
}
}
/**/ /// <Summary>
///Memorandum
/// </Summary>
Public Class Roundmemento
{
Internal Point centerpoint;
Internal Int Radius;
Public Roundmemento ()
{
}
Internal Void Setstate (point centerpoint, Int Radius)
{
This. Centerpoint=Centerpoint;
This. Radius=Radius;
}
}
}
Namespace Designpattern. Memento
{
Public Class Graphicssystem
{
Round round = New Round ( New Point (), 10 );
Ilist < Roundmemento > Mementos;
Public Graphicssystem ()
{
Mementos= NewList<Roundmemento>();
}
Public Void Process ()
{
Mementos. Add (round. creatememento ());
//Operation circle
}
Public Void Undo ( Int Index)
{
Round. setmemento (mementos [Index]);
}
}
}
Key Points :
1. Memento stores the internal status of the originator object and restores the status of the original object as needed. This mode applies to "information that is managed by the primary but must be stored outside the primary ".
2. When implementing this mode, you must prevent objects other than the primary object from accessing the memorandum object. The memorandum object has two interfaces: one is the wide interface used by the primary object and the other is the narrow interface used by other objects.
3. When implementing this mode, you must consider the efficiency of copying object States. If the object overhead is large, you can use an incremental change to improve this mode.