Store/Restore snapshot/state of entire application

好久不见. 提交于 2020-01-15 09:07:32

问题


I want to store the entire application state and then restore it on the next start. Is there a library which would make it easier for me? Or does anyone of you have any suggestions?

Standalone Application


回答1:


There is a design pattern that is used for your purpouse, and it is the Memento Pattern.

The memento pattern is implemented with three objects: the originator, a caretaker and a memento. The originator is some object that has an internal state. The caretaker is going to do something to the originator, but wants to be able to undo the change. The caretaker first asks the originator for a memento object. Then it does whatever operation (or sequence of operations) it was going to do. To roll back to the state before the operations, it returns the memento object to the originator. The memento object itself is an opaque object (one which the caretaker cannot, or should not, change). - Wikipedia

You can read the example provided in the wiki page to understand how to use it inside your code.

If you want to save the state of an object as a file, and have it avaiable even after the execution of your program is over, you should implement the Serializable interface in the class you want to store.

Example:

public class Example implements Serializable
    {

    }

and where you instantiate that class:

try{

    Example c = new Example();
    FileOutputStream fout = new FileOutputStream("YOURPATH");
    ObjectOutputStream oos = new ObjectOutputStream(fout);   
    oos.writeObject(c);
    oos.close();
    System.out.println("Done");

   }catch(Exception ex){
       ex.printStackTrace();
   }


来源:https://stackoverflow.com/questions/38904182/store-restore-snapshot-state-of-entire-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!