Save/Store "State" implementation ideas

I am trying to figure out the “best” way to implement this…

Problem : I have a Master Class “A” the has a dozen properties that represent things like fontname, fontsize, colors, linestyle etc.
Various methods in this class need to

  • “save the current state” (ie. the current values of all those properties),
  • then the method will assign new values to one or more of the properties, but will need the current value of any property not specifically changed
  • do some work
  • “restore the current state” (ie. put all the values back to what there were)…

We use classes that contain dictionaries for this, with computed properties for coding accuracy. Disposable variables are simply variables on the class (not written into the dictionary).

There’s also a couple of events on the core class so that extra data can be encoded/decoded if needs be.

This way they can either be written out and read in using declares for plists or JSON.

With this technique you can store all the values by duplicating the dictionary or serializing it to another data type (i.e. string), do your thing and then restore the original values by setting the dictionary back.

Create a method called CopyTo(newClass As ClassName), put in there all your code to copy properties etc.

Sub CopyTo(newClass as Class1) newClass.Colour = me.Colour End Sub

Inside a method that you need to do something and restore values of the original class do the following:

[code]Sub DoSomething()
Dim tmp as New Class1

me.CopyTo(tmp)

tmp.Colour = “Blue”

system.DebugLog(tmp.Colour)
End Sub
[/code]

You can then work inside your method using tmp and properties etc of the original class wont be altered. When tmp goes out of scope it will be garbage collected and you dont have to write addition code etc, just keep CopyTo updated with stuff you need to copy across.

Ive used both methods above in the past.

If there is literally ‘how it looks now’, and ‘what it looked like before I started’, then the simplest way is to create a .clone method that creates a new object of the same class, and duplicates the existing values.
Call it ‘backup’

Then if you want to restore state, copy all 12 values from backup to ‘me’

For larger sets of properties, I’ve something that serialises them into XML.
I turn the XML into a string and maintain an array as a LIFO stack
That allows me to have an undo chain… every change causes something to be added to the stack.
Every undo pulls from the stack , ditches the last entry, and resets the properties to be what was in the pulled definition.
JSON would work too, and I know you have an ‘INI equivalent’ method you were using some years back which would probably work in the same way

A class using introspection should work here
Try this (tweak as necessary)