MATLAB Object-Oriented Programming

(Joyce) #1

Basic saveobj and loadobj Pattern


In this section...
“Using saveobj and loadobj” on page 13-19
“Handle Load Problems” on page 13-20

Using saveobj and loadobj


Depending on the requirements of your class, there are various ways you can use
saveobj and loadobj methods. This pattern is a flexible way to solve problems that you
cannot address by simpler means.

The basic process is:


  • Use saveobj to save all essential data in a struct and do not save the object.

  • Use loadobj to reconstruct the object from the saved data.


This approach is not useful in cases where you cannot save property values in a struct
field. Data that you cannot save, such as a file identifier, you can possibly regenerate in
the loadobj method.

saveobj

For this pattern, define saveobj as an ordinary method that accepts an object of the
class and returns a struct.


  • Copy each property value to a structure field of the same name.

  • You can save only the data that is necessary to rebuild the object. Avoid saving whole
    objects hierarchies, such as those created by graphs.


methods
function s = saveobj(obj)
s.Prop1 = obj.Prop1;
s.Prop2 = obj.Prop2
s.Data = obj.GraphHandle.YData;
end
end

Basic saveobj and loadobj Pattern
Free download pdf