Java Design Patterns Hundred Cases-Memo mode __java

Source: Internet
Author: User
Tags anonymous save file static class stringbuffer

This article source code see: Https://github.com/get-set/get-designpatterns/tree/master/memento

Memo Mode (Memento pattern) is also called snapshot mode (Snapshot pattern), which is the behavior pattern of the object. Used to save a state of an object in order to recover the object at the appropriate time. Example

I prefer the term "snapshot mode" because it is more image. Today's example is also from the "snapshot".

Virtual machines are estimated to have been used by most people, such as the fact that I started using Deepin Linux last year (yes, it was such a hard implant ad, deepin really good, highly recommended ~) as the main operating system. However, there are many applications in Windows, such as Office series and Adobe series, I do not want Linux and Windows dual system switching, the best way is to install Windows virtual machines in Linux.

The virtual machine has a very good feature is "snapshot", the system to the most comfortable state, loaded with the software, and then take a snapshot, you can save the current system state, once the system has broken, and then use this snapshot to restore the good.

The virtual machine can be snapped at power-on and shutdown state.
* Shutdown state, save the status of the virtual disk is good, like our physical machine to save the hard disk, switch to another physical machine to start;
* In the boot state, in addition to the virtual disk storage snapshots, the state of the memory is also saved as a memory snapshot to the physical storage, the system after the snapshot is still in a running state, the memory snap is reloaded into memory, so the open application continues the state execution of the snapshot, like the physical machine hibernation.

If you want to simulate this process, you can use the memo mode/Snapshot mode (hereinafter called "snapshot Mode").

Before we go down the handwriting code, let's take a look at the characteristics of the user when using the snapshot feature:
* Users do not have to care about the details of the snapshot. Users only need to save the status of the virtual machine when the "snapshot" button can be, specifically saved what content is not care; the same is true for recovering snapshots.
* Users cannot modify the contents of the snapshot at will. Both VirtualBox and VMware will not provide users with the ability to modify the contents of the snapshot, but the user is also hard to get involved in. Users only need to know the snapshot tree or the snapshot list of their snapshots.

This is a typical feature of the application scenario for snapshot mode. That is , for the consumer of the object state (Memo/snapshot), it is not concerned with how to specifically save and restore the status of the target object, and in most cases, for security reasons, it does not expose too much state-based processing details to the consumer.

Based on this, for users, just need to know that there is a "snapshot" of such a magical use of the thing is good:

Snapshot.java

Public interface Snapshot {
}

Yes, that's it. An empty interface, or it only contains the necessary operations.

For virtual machines, multiple operations are supported, including snapshots and recovery to a snapshot:

Virtualmachine.java

public class Virtualmachine {//virtual machine name private String name;
    Virtual machine configuration private String devices;
    Virtual machine memory content, simplified to a String list private list<string> memory;
    The virtual machine stores the content and simplifies it to a String list private list<string> storage;

    Virtual machine status Private String state;
        Public Virtualmachine (string name, string devices) {this.name = name;
        This.devices = devices;
        This.memory = new arraylist<string> ();
        This.storage = new arraylist<string> ();
    This.state = "created"; /** * Create virtual machine * @param name virtual machine names * @param devices Virtual machine configuration * * Public virtualmachine CREATEVM (St
    ring name, String devices} {return new Virtualmachine (name, devices); //power-on, shutdown, pause, restore ... Slightly/** * Open application, loaded into memory, used to simulate content in memory */public void Openapp (String appName) {if ("Running". Equals (STA
            TE)) {This.memory.add (appName); SYSTEM.OUT.PRINTLN ("virtual machine" + name + "Open application:" + AppName); /** * Closes the application and deletes it from memory to simulate content in memory/public void Closeapp (String appName) {if ("Running". EQ
            Uals (state)) {this.memory.remove (appName);
        SYSTEM.OUT.PRINTLN ("virtual machine" + name + "Close application:" + appName); }/** * Saves the file and writes it to the virtual disk to simulate the contents of the store/public void SaveFile (String file) {if ("running"). Equal
            S (state)) {this.storage.add (file);
        System.out.println (save file in "virtual machine" + name +): "+ file"; /** * Deletes files from the virtual disk to simulate the contents of the store/public void Delfile (String file) {if ("running"). Equa
            LS (state)) {this.storage.remove (file);
        SYSTEM.OUT.PRINTLN ("virtual machine" + name + "Delete files:" + file);
     }/** * Take a snapshot, if the boot state will save the memory snapshot and storage snapshots, if the shutdown state, save only the snapshot can be stored. */Public Snapshot takesnapshot () {if ("Shutdown". Equals (state)) {return new vmsnapshot (null, NE
     W arraylist<string> (storage));   else {return new vmsnapshot (new arraylist<string> (memory), new arraylist<string> (storage));  }/** * Recovery snapshot/public void Restoresnapshot (Snapshot Snapshot) {vmsnapshot TMP =
        (vmsnapshot) Snapshot;
        This.memory = new Arraylist<string> (Tmp.getmemory ());
        This.storage = new Arraylist<string> (Tmp.getstorage ());
        if (tmp.getmemory () = = null) {this.state = "shutdown";
        @Override public String toString () {StringBuffer stringbuffer = new StringBuffer (); Stringbuffer.append ("------\n[virtual Machine" "+ Name +" "] configured to" "+ Devices +" "," + "current status is:" + state + ".
        ");
            if ("Running". Equals (state)) {stringbuffer.append ("\ n) currently running applications are:" + memory.tostring ());
        Stringbuffer.append ("\ n recently saved files are:" + storage.tostring ());
        } stringbuffer.append ("\ n------");
    return stringbuffer.tostring ();
 }

}

such as on the virtual machine related operations, which boot, shutdown, pause, restore, and so on, can refer to the source code. For simplicity, it affects the loading and deletion of content in memory using open and close applications, and saves and deletes files to affect the additions and deletions of content on storage media such as disks.

The Takesnapshot () method and the Restoresnapshot (Snapshot) method are used to save and restore the state of the virtual machine, where the state is the memory snapshot and the storage snapshot. So the specific snapshot implementation class needs to have memory and storage attributes. No incremental snapshots of storage are considered here.

Vmsnapshot.java

public class Vmsnapshot implements Snapshot {
    private list<string> memory;
    Private list<string> storage;

    Public Vmsnapshot (list<string> memory, list<string> storage) {
        this.memory = memory;
        This.storage = storage;
    }

    Getters & Setters
}

But the problem with this implementation is that for "users" it exposes the contents and operations of the virtual machine snapshot, and users can create snapshots themselves without the virtualization software (new Vmsnapshot) or arbitrarily modify the snapshot content. This is clearly not the hope of VMware or VirtualBox. Therefore, vmsnapshot must be invisible to the user.

At this point, you need to place the Vmsnapshot class in the contents of the Virtualmachine class and declare it as "private static inner class":

Virtualmachine.java

public class Virtualmachine {
    ...
    private static class Vmsnapshot implements Snapshot {
        ...}}

A simple stroke of inner class:
* The static inner class is the simplest inner class, which can be understood as a normal class, but just within another class, the only difference from the ordinary class is that the inner class can access the private members of its external class;
* Non-static Inner class is more complex, its object and external class objects have one by one corresponding relationship, can not be independent of the external class object and exist, also can access the private members of its external class;
* Anonymous inner class, is to temporarily instantiate an interface or abstract class, so you must complement the full interface or abstract methods in a class, because it is temporary, so there is no need to rename. For an interface with only one method, its anonymous inner class can be replaced with a lambda expression, more concise.

For users, this uses the snapshot feature of the virtual machine:

User.java

public class User {public
    static void Main (string[] args) {
        stack<snapshot> snapshots = new STACK<SNAPSH Ot> ();

        Virtualmachine Ubuntu = new Virtualmachine ("Ubuntu", "a 4 kernel cpu,8g memory, 80G hard Drive");

        Ubuntu.startup ();
        Ubuntu.openapp ("NetEase cloud Music");
        Ubuntu.openapp ("Google browser");
        Ubuntu.savefile ("/tmp/test.txt");
        System.out.println (Ubuntu);

        Snapshot
        Snapshots.push (Ubuntu.takesnapshot ());

        Ubuntu.closeapp ("NetEase cloud Music");
        Ubuntu.openapp ("IntelliJ idea");
        Ubuntu.delfile ("/tmp/test.txt");
        Ubuntu.savefile ("/workspace/hello.java");
        System.out.println (Ubuntu);

        Restore Snapshot
        ubuntu.restoresnapshot (Snapshots.peek ());
        System.out.println ("Revert to the most recent snapshot ...");

        System.out.println (Ubuntu);
    }

The output is as follows:

Virtual machine Ubuntu started
virtual machine Ubuntu Open application: NetEase Cloud Music
Virtual machine Ubuntu open application: Google browser
virtual machine ubuntu save file:/tmp/test.txt
------
[ Virtual machine "Ubuntu" is configured as "a 4 kernel cpu,8g memory, 80G hard Drive", the current status is: running.
    currently operating applications are: [NetEase cloud Music, Google browser]
    recently saved files have: [/tmp/test.txt]
------
virtual machine ubuntu shutdown application: NetEase Cloud Music
Virtual machine Ubuntu Open application: IntelliJ idea
virtual machine ubuntu Delete file:/tmp/test.txt
virtual machine ubuntu save file:/workspace/hello.java
- ----
[virtual machine "Ubuntu"] configured as "A 4 core cpu,8g memory, 80G hard Drive", the current status is: running.
    currently running applications are: [Google Browser, IntelliJ idea]
    recently saved files are: [/workspace/hello.java]
------
back to the most recent snapshot ...
------
[Virtual machine "Ubuntu"] configured as "A 4 core cpu,8g memory, 80G hard Drive", the current status is: running.
    currently operating applications are: [NetEase cloud Music, Google browser]
    recently saved files are: [/tmp/test.txt]
------

After the courseware recovers the snapshot, the contents of both memory and disk are restored. Summary

The above example summarizes several features of the memo pattern: Capturing the internal state of an object without destroying the encapsulation and saving the state outside the object. From the implementation, the static inner class is used instead of the non-static inner class. Status (Memo/snapshot) guarantees that its contents are not read or manipulated by objects other than objects that are saved. From the implementation, use a private static inner class. In the example, user cannot access or manipulate virtualmachine.vmsnapshot. Role of Memo mode:
Originator, which is the class of the saved state, the virtualmachine in the example, the Memento, the state of the preservation, the virtualmachine.vmsnapshot in the example, the caretaker, in some implementation scenarios, There will also be a class dedicated to saving memento objects, which can be imagined as an example of adding a "virtual machine management software" role (such as VirtualBox or VMware) between users and virtual machines, with virtual machine management software to maintain all snapshots, which is well understood. Design patterns do not need rote relationships and roles ~

Through the characteristics of the above, you can see that the memo mode is usually applied to the state of originator must be stored outside the place, but also must be read by the originator state of the scene. The benefit of the memo mode is that it can effectively shield originator internal information. The benefit is also obvious, take a snapshot, if you do not consider the "incremental snapshot", then the snapshot of the save and restore may be a very resource-intensive operation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.