>> I'm trying to find information on using singletons in AS3/Flex. I've
>> got an .AS file set up but I'm having issues calling the data/functions
>> within that function in other classes. Does anyone have a good resource
>> on the web for creating and using singletons?
As others have probably pointed out, it sounds like you may be trying
to use a singleton to solve an architectural issue possibly not best
solved with a singleton. But, if singleton is appropriate...
Don't make it more complicated than it needs to be. Everyone seems to
do that with singletons, which is unfortunate since singletons should
be so rarely used anyway. Just create a class that creates and returns
an instance on first access, then returns that instance on further
access. If you're worried about other developers constructing multiple
instances of your class, then just include a test in the constructor
and have it throw an error or assert.
Don't worry about making it *impossible* to create multiple
instances... it's just not worth the effort. If people are determined
to use your classes incorrectly and disregard warnings and errors,
etc, then they're digging their own grave.
Here's the implementation I use:
public class Singleton {
private static _instance:Singleton;
public function get instance():Singleton {
if (_instance == null) _instance = new Singleton();
return _instance;
}
public function Singleton() {
if (_instance != null) throw new Error("This class is a singleton.
Instance already created.");
}
}
Troy.