Behavioral patterns (X) memo mode (Memento)

Motivation (Motivate)

   In the software building process, the state of some of the objects in the conversion process, may be required for some applications demand can be placed back in the state where a point prior to the subject. If you use some of the public interface to allow other objects to get the status of an object, the object will expose the details of implementation.
  How to achieve the object of a good state of preservation and restoration, but at the same time will not be destroyed encapsulation of the object itself?

Intent (Intent)

   Without violating encapsulation, capture and externalize the internal state of an object, and save the state outside of the object (if not the key point, in fact, a deep copy can solve the problem). So that later you can restore the object to a previously saved state. - "Design Patterns" GoF

FIG structure (Structure)


Composition mode

    As can be seen, there are the following roles in the structure of FIG memo mode:
(1), the sponsor role (Originator): record the internal state of the current moment, it is responsible for creating and restoring memo data. Responsible for creating a memorandum of Memento, the current time to record their own internal states, and can be used to restore internal memo states. Originator Memento [sponsor] [memo] may decide according to what needs to be stored inside their own state.
(2), memorandum role (Memento): responsible for storing the sponsors object's internal state, during the state available to sponsor restoration needs, and can prevent object access memo other than Originator. Memorandum has two interfaces: Caretaker [management roles can only see the memorandum of narrow interface, he can only pass the memo to other objects. Originator promoters [] but it can be seen memo wide interface, which allows access to all data prior to return to the desired state.
(3), the manager role (Caretaker): responsible for saving memo objects. Responsible memorandum Memento, Memento content can not be accessed or operations.

Memo mode code implements

    Today we use the example of a backup phone book to illustrate the realization of the memo mode. Codes are as follows:

static void Main(string[] args)
{
    List<ContactPerson> persons = new List<ContactPerson>()
            {
                new ContactPerson() { Name="黄飞鸿", MobileNumber = "13533332222"},
                new ContactPerson() { Name="方世玉", MobileNumber = "13966554433"},
                new ContactPerson() { Name="洪熙官", MobileNumber = "13198765544"}
            };

    // phone list of sponsors 
    MobileBackOriginator mobileOriginator = new new MobileBackOriginator (persons);
    mobileOriginator.Show();

    // create memos and save the memo object 
    MementoManager Manager = new new MementoManager ();
    manager.ContactPersonMemento = mobileOriginator.CreateMemento();

    // Change the sponsor contact list 
    Console.WriteLine ( " ---- -------- removes the last contact " );
    mobileOriginator.ContactPersonList.RemoveAt(2);
    mobileOriginator.Show();

    // restored to its original state 
    Console.WriteLine ( " ------- ------ restore your contact list " );
    mobileOriginator.RestoreMemento(manager.ContactPersonMemento);
    mobileOriginator.Show();

}
// contact - data to be backed up, is a state data, no operating 
public  Sealed  class ContactPerson
{
    // name 
    public  String the Name { GET ; SET ;}

    // telephone number 
    public  String MobileNumber { GET ; SET ;}
}

// sponsor - the equivalent of [sponsor roles Originator 
public  Sealed  class MobileBackOriginator
{
    // promoters need to preserve the internal state of the 
    Private List <ContactPerson> _personList;


    public List<ContactPerson> ContactPersonList
    {
        get
        {
            return this._personList;
        }

        set
        {
            this._personList = value;
        }
    }
    // phone list initialization needs to be backed 
    public MobileBackOriginator (List <ContactPerson> personList)
    {
        if (personList != null)
        {
            this._personList = personList;
        }
        else
        {
            the throw  new new ArgumentNullException ( " parameter can not be empty! " );
        }
    }

    // Create a memo object instance, will save the current contact list to be saved to the memo objects in 
    public ContactPersonMemento CreateMemento ()
    {
        return new ContactPersonMemento(new List<ContactPerson>(this._personList));
    }

    // to back up data is restored to the memorandum contact list 
    public  void RestoreMemento (ContactPersonMemento Memento)
    {
        this.ContactPersonList = memento.ContactPersonListBack;
    }

    public void Show()
    {
        Console.WriteLine ( " contact list {0} There are personal, they are: " , ContactPersonList.Count);
         foreach (ContactPerson the p- in ContactPersonList)
        {
            Console.WriteLine ( " Name: Number {0}: {}. 1 " , p.Name, p.MobileNumber);
        }
    }
}

// memo object, which holds state data, the object was saved specific state data - the equivalent of [memorandum roles Memeto 
public  Sealed  class ContactPersonMemento
{
    // save the promoters to create a phone list data, the so-called state 
    public List <ContactPerson> ContactPersonListBack { GET ; Private  the SET ;}

    public ContactPersonMemento(List<ContactPerson> personList)
    {
        ContactPersonListBack = personList;
    }
}

// management role, it can manage [memo] object if it is [memo] to save multiple objects, of course, you can add, delete and other management process to save the equivalent of objects --- [Manager roles Caretaker 
public  Sealed  class MementoManager
{
    // If you want to save the memo [plurality] objects, or may be preserved by the dictionary stack, stack object can reflect the sequence of stored objects
     @ example: public the Dictionary <String, ContactPersonMemento> {GET ContactPersonMementoDictionary; SET;} 
    public ContactPersonMemento ContactPersonMemento { GET ; SET ;}
}

Achieve points memo mode:

        Internal state memo (Memento) primary memory device (Originator) object, to restore the original state when required hair. Memento mode is suitable for "Hair former management, but the information must be stored outside the primary's."
  In the implementation Memento mode, to prevent objects other than object access memo primary device. Memo object has two interfaces, a wide use of the primary interfaces; is a narrow interface of other objects. In implementing the Memento pattern, to consider the efficiency of the state's copy of the object, if the object overhead is relatively large, you can use some incremental changes (that is, only remember the state change) to improve the Memento pattern.
  We can also use serialized manner memorandum. After serialization, we can save it to a local temporary database, files, processes, and other outside processes.

(1), the main advantages of the memo mode are:

            1], if an operator error damaged the integrity of the data, then you can use the memo mode to restore the data to its original correct data.
            2], state data stored in the backup role than sponsors, so there is no need for the sponsor to manage the status of each backup. But it is managed by the memorandum role, and the role in turn memorandum manager role management, in line with the principle of single responsibility.
            3], provides an implementation mechanism for the recovery of the state, so that the user can easily return to a specific historical step, when a new state is invalid or there is a problem, you can use previously stored memo will state recovery.
            4] to achieve the encapsulation information, a memo object is an indication of the primary object, other code will not be altered, this model simplifies the primary object, only the memo is stored in the primary state, using the stack to store the memo object can implement multiple undo operations, through the people responsible for the definition of a set of objects to store multiple memos.
            5], this model simplifies the launch humans. Sponsor no longer need to manage and save its internal state of a version of the client can manage their own versions of these states they need.
            6], when the role of state sponsors of change, there may be invalid in this state, this time we can use temporarily stored memo will state recovery.

(2) major disadvantage memo mode are:

            1], in a practical system, you may need to maintain multiple backups, the need for additional resources, so consumption of resources more serious. Excessive consumption of resources, if the class member variables too, will inevitably take up a lot of memory, and save time every state of the object needs to consume memory resources, if we know that it is easy to understand why some software provides an undo function required at run-time memory and hard disk space is relatively large.
            2], if the state needs to fully sponsor the role of objects stored in the memo, then the resource consumption above memo objects will be very expensive.
     3], when the role of the head of a memorandum of stored, the person in charge may not know this state will take up much storage space, which can not remind a user operation is very expensive.
     4], when the role of state sponsors of change, it is possible that the agreement is invalid. If the state changes the success rate is not high, it is better to take "if" protocol mode.

(3), in the following case may be considered to use the memo mode:

          1], if the system needs to provide rollback operation mode it is suitable to use memo. For example, a text editor Ctrl + Z undo operation implementation, the database transaction operations.
          2], the state of an object to save time or a certain part of the state, so that it can be restored later when necessary to its previous state.
          3], if an interface to allow other objects to get these states, will expose implementation details and break the object encapsulation object, an object does not want the outside world to directly access its internal state, it can be accessed indirectly through its internal state responsible person.
          4], and sometimes some internal information sponsor of the object must be stored in places other than the sponsor of the object, but the object must be read by the promoters themselves, then, using the Memo mode can be complicated sponsor inside information to other objects shielded, so that the boundary can be appropriately held in the package.

Encapsulation (4) memorandum

         1], in order to ensure that the packaging of the memorandum, in addition to the primary device, other classes can not nor should visit the memorandum class, in the actual development, the relationship between the primary with the memorandum are very special, they want to share information without letting other classes know that the way to achieve due to different programming languages ​​and different.

(5) multi-backup achieve

         1], the people responsible for the definition of a set of objects to store multiple states, and can easily return to a historical state.
         2], when a backup object can do some tokens, these tokens called checkpoint (Check Point). When implemented using HashMap and the like may be used to set the check points Key.

Similarities and Differences (6) Memento Command Mode and Mode

      Memento memo mode and command mode Command in fact, there are some subtle differences, let us look at their similarities and differences now. While both support Undo operation, but is packaged Command of behavior, Memento is reserved for the state of the object, which is different on purpose. They also support different levels of Undo operations, Command is the operation of the action sequences, Memento is operating on the behavior of states. Stored command mode command is specific promoters (behavior corresponding to a command), and sponsor are stored memo mode state (the state corresponding to the data structure, such as a property). Grasp the details, understand the mode of application scenarios, which would allow us to better service mode.

Implement .NET memo mode

     In the current framework which Net realized memo mode has not been found, but it seems his skill is not enough, need effort. Personal understanding, this model seems to be used more in the business system which, similar to Word, Excel and other tools can undo function, in fact, many software has this feature, the software execution time, always in their own state storage If an error occurs, or need to revoke when you can perform related operations.

Guess you like

Origin www.cnblogs.com/springsnow/p/11362213.html