Global Static classes (or alternative?)
13 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hi there,
I am writing a fairly large script in Matlab 2010b that depends heavily on objects. Most of these objects have methods and properties, a few contain other objects.
What I want is to be able to manipulate some variables and objects from anywhere in my code. Due to the strict scope of variables in Matlab, the only way to do this is by passing the variables I might want to read/edit between every method. This can get very cumbersome indeed, expecially if I have a few objects and data I need accessed.
Two examples of this might be:
- A logging output file handle. I open a file handle right at the start of my script. I want all the methods in all the objects to write to this log file. At the moment, I pass the file handle by reference deep into the bowels of my code. Technically correct, but very ugly
- A 'database' object that contains a set of data that is read by a number of methods. This is an object now but could equally be a matrix (there are no methods). Again, if I want to read this data, I need to pass it deep into my object tree manually.
What I was hoping for was some manner of global (possibly static) object. I would set these up at the start of my script and have them readable/writable from any point in my code, even if the variable scope changes. It's not good practice, but for my purposes I reckon it will be safe enough.
However, global variables don't appear to persist between scope changes and global vars I declare (even primitives) are not accessible once the scope changes. Should this be the case?
Is there a better way to do this?
Thanks!
0 Commenti
Risposta accettata
Joan Puig
il 4 Apr 2011
Hi Alexander,
I think you could try to use this inside your class definition:
methods (Static)
function singleton = getInstance
persistent local
if isempty(local)
local = ... Initialize your variable
end
singleton = local;
end
end
Because it is a static method it can be used from anywhere in the code just by typing
MyClass.getInstance();
On a side note, MyClass should probably inherit from handle.
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Performance and Memory in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!