I've made a simple testcase with a singleton and three Flex projects:
1. MainApp
2. ModuleOne
3. ModuleTwo
MainApp loads ModuleOne which loads ModuleTwo (it could also load both
modules, the behaviour I describe below seems to be the same in both cases).
I have created a TestSingleton.as which implements the Singleton pattern (as
far as it can be tanken in AS anyway ..)
Here's TestSingleton.as's getInstance() method:
/**
* Get the only instance of the TestSingleton
* @return TestSingleton instance
**/
public static function getInstance():TestSingleton
{
if (instance == null)
{
instance = new TestSingleton();
trace("TestSingleton - instance was null, so created new instance");
} else {
trace("TestSingleton already instanciated, so returning instance..");
}
return instance;
}
If I put the singleton in MainApp, and then getInstance() it from ModuleOne
and ModuleTwo I'll get this in my trace:
[SWF] C:\dev\FlexWorkspace\ModuleTestMainApp\bin\ModuleTestModuleOne-
debug.swf - 450,372 bytes after decompression
TestSingleton - instance was null, so created new instance
[SWF] C:\dev\FlexWorkspace\ModuleTestMainApp\bin\ModuleTestModuleTwo-
debug.swf - 446,193 bytes after decompression
TestSingleton already instanciated, so returning instance..
.. which is the expected behaviour.
However, if I put TestSingleton.as in ModuleTwo, I get this:
[SWF] C:\dev\FlexWorkspace\ModuleTestMainApp\bin\ModuleTestModuleOne-
debug.swf - 450,372 bytes after decompression
TestSingleton - instance was null, so created new instance
[SWF] C:\dev\FlexWorkspace\ModuleTestMainApp\bin\ModuleTestModuleTwo-
debug.swf - 446,193 bytes after decompression
TestSingleton - instance was null, so created new instance
.. it doesn't behave as a singleton anymore ..
Can anyone explain why? :-)
--
========================
http://www.juicability.com - flex blog
http://www.43min.com - funny movies