Reputation: 1294
I am trying to create a class that transparently loads and saves a class to a form of persistent storage.
Currently I am using the pattern:
get
{
return _data;
}
set
{
//Do change logic
_data = value;
}
This works well for when the _data object is first set, as the set accessor is being called. However, if get is used a reference is returned. Any changes to the data objects properties via this reference are not detected as at no point is the set accessor called.
I would call the persistence logic in the get accessor, but at this stage the changes are yet to be made. I have also considered using a destructor to save all the changes upon termination, but I believe it is bad practise to do blocking operations in a destructor?
Is there a better pattern or methodology that would call the change logic for this scenario?
Upvotes: 0
Views: 280
Reputation: 61339
Normally, I would have a "Save" function that does this (on a click or timer or whatever). That way you limit your hits to persistence.
If you really want to save on every property change, consider having the affected object implement INotifyPropertyChanged
. It is usually used for bindings, but you can subscribe to the events just as well! In the event handler you can check the name of the property that was changed and run your save logic.
Upvotes: 3