Definition: capture and save the internal state of an object without damaging the encapsulation, so that the object can be restored to the original saved state. As in many software applications, pressing Ctrl-Z will cancel the last user operation, that is, the Undo operation.
Generally, there are three types of memorandum modes:
Memento: Memorandum; Originator: Master; Caretaker: viewer, in charge of the memorandum.
[Csharp]
Using System;
Using System. Collections. Generic;
Using System. Text;
Namespace memorandum _ game memory progress
{
Class GameRole
{
Private int vit; // vitality
Public int Vit
{
Get {return vit ;}
Set {vit = value ;}
}
Private int atk; // Attack Capability
Public int Atk
{
Get {return atk ;}
Set {atk = value ;}
}
Private int def; // defense capability
Public int Def
{
Get {return def ;}
Set {def = value ;}
}
Public Memento savemento () // Save the internal status
{
Return (new Memento (vit, atk, def ));
}
Public void RestoreMemento (Memento memento) // restore the status
{
This. vit = memento. Vit;
This. atk = memento. Atk;
This. def = memento. Def;
}
Public void Show ()
{
Console. WriteLine ("current role status :");
Console. WriteLine ("vitality: {0}", this. vit );
Console. WriteLine ("Attack Power: {0}", this. atk );
Console. WriteLine ("defensive force: {0}", this. def );
}
}
Class Memento
{
Private int vit; // vitality
Public int Vit
{
Get {return vit ;}
Set {vit = value ;}
}
Private int atk; // Attack Capability
Public int Atk
{
Get {return atk ;}
Set {atk = value ;}
}
Private int def; // defense capability
Public int Def
{
Get {return def ;}
Set {def = value ;}
}
Public Memento (int vit, int atk, int def)
{
This. vit = vit;
This. atk = atk;
This. def = def;
}
}
Class Caretaker
{
Private Memento memento;
Public Memento
{
Get {return memento ;}
Set {memento = value ;}
}
}
Class Program
{
Static void Main (string [] args)
{
GameRole g = new GameRole ();
G. vi t = 100;
G. Atk = 100;
G. Def = 100;
G. Show ();
Caretaker c = new Caretaker ();
C. Memento = g. SaveMemento ();
G. vi t = 200;
G. Atk = 200;
G. Def = 200;
G. Show ();
G. RestoreMemento (c. Memento );
G. Show ();
Console. Read ();
}
}
}
If you want to implement multiple Undo (Undo) or Ctrl-Z operations, you only need to change a single memo in the Caretaker class to a memorandum vector. The last element in each orientation volume during restoration is used for restoration.