Four roles: Originator, Memento, Caretaker, and Client)
Originator: a prototype that requires a memorandum to remember its internal state. You can save the status of this category to the memorandum, or restore the status through the memorandum.
Memento: maintains the internal status of the primary machine,
Caretaker: The memorandum of care, which cannot be modified.
Client: Execute the master node to save the Memorandum and restore it.
Implementation: The client produces the primary machine. When the primary machine saves the memorandum to the viewer, the primary machine continues to change its status, when necessary, obtain the saved status from the memo of the viewer to update the status of the primary server.
Class diagram:
650) this. width = 650; "border =" 0 "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/1R13L101-0.gif "/>
Application scenarios: Phone memo saved.
Analysis: When someone's phone number is saved to the memo, if it needs to be restored, the custodian can call the memo to restore the original class.
In the console, we will demonstrate how to use Memento Pattern:
1. Originator ):
- // Originator
- Class PhoneOriginator
- {
- Public string Name {get; set ;}
- Public string Number {get; set ;}
- Public PhoneMemento SaveMemento ()
- {
- Return new PhoneMemento (Name, Number );
- }
- Public void ResumeMemento (phonemento PhoneMemento)
- {
- This. Name = phonemento. Name;
- This. Number = phonemento. Number;
- }
- Public void Display ()
- {
- Console. WriteLine ("------------------");
- Console. WriteLine (Name );
- Console. WriteLine (Number );
- }
- }
Ii. Memorandum (Memento ):
- // Memento Memorandum
- Class PhoneMemento
- {
- Public string Name {get; set ;}
- Public string Number {get; set ;}
- Public PhoneMemento (string name, string number)
- {
- This. Name = name;
- This. Number = number;
- }
- }
3. Caretaker ):
- // Caretaker Viewer
- Class PhoneCaretaker
- {
- Public PhoneMemento Memento {set; get ;}
- }
4. Client ):
- // Client
- Class Program
- {
- Static void Main (string [] args)
- {
- PhoneOriginator po = new PhoneOriginator ();
- Po. Name = "James ";
- Po. Number = "13880191995 ";
- Po. Display ();
- PhoneCaretaker pcaretaker = new PhoneCaretaker ();
- Pcaretaker. Memento = po. savemento ();
-
- Po. Name = "Lili ";
- Po. Number = "13669595999 ";
- Po. Display ();
-
- Po. ResumeMemento (pcaretaker. Memento );
- Po. Display ();
- Console. ReadLine ();
-
- }
- }
To download the source code, click MementoPattern.rar.