Reputation: 337
I have an editor and some files opened. I do some changes and don't save them. For some reason my app crashes.
After that I run the app again and want the editor to show the message like: "The system crashed unexpectedly. There are some changes in your files that weren't saved. Do you want to recover them or load the original state?"
I want to implement something like that.
The first thought was to create a Temp folder which is used to keep modified copies of the original files. These copies are updated every change in the editor or in regular time as autosave. When I click Save, the temp copy just replaces the original. If system crashes I choose either the temp or the original to load.
The second one is to save change log in associated file as for Undo/Redo mechanism and redo things step by step if needed. But it's too expensive and hard to implement in comparison.
And the third is to save modified data copy in the same file with original data (if data is not too big of course) and act like in the first case but without Temp folder.
So are there any patterns, typical approaches or data structures for that issue?
Upvotes: 1
Views: 31
Reputation: 725
You can use an audit log (https://martinfowler.com/eaaDev/timeNarrative.html), so you should track the changes you did to a file (the differences). This record can be represented in a row in a database table or in a sequential structure in one file. Another way to do this is through event sourcing (https://kickstarter.engineering/event-sourcing-made-simple-4a2625113224) for your App, where you can keep in memory the db the tracking, using events to keep the differences. You can limit the stored events to a maximum as a buffer, so you can undo until one step back.
If you want to go deeper, you can inspect this https://wyag.thb.lt/, and try to take ideas to develop an autocommit content tracking system to add to your editor based on GIT principles.
But if you are looking for "an easy way", you can use the memento pattern (https://en.wikipedia.org/wiki/Memento_pattern) mixed with the observer pattern (https://en.wikipedia.org/wiki/Observer_pattern), to save the observed changes over the files using a Caretaker where each originator is each file editor, and each memento is a record with the last copy.
Other references:
Upvotes: 1