Beware of singleton in Flex modules

Flex Published on March 12, 2010 by Andrea Bresolin 3 Comments »

Example 1 (without importing the singleton class in the main application – module-wide singleton):

Live demoSource code (LICENSE)

Example 2 (singleton class imported in the main application – application-wide singleton):

Live demoSource code (LICENSE)

This is something I recently discovered during some tests and it’s something to consider when using the singleton design pattern inside Flex modules. First of all, here is an example implementation of the singleton pattern in Flex:

public class SingletonClass
{
	protected static var _instance: SingletonClass = null;

	public static function getInstance(): SingletonClass
	{
		if (_instance == null)
		{
			_instance = new SingletonClass();
		}

		return _instance;
	}
}

This class can be simply used to get the singleton instance with a line like this:

var theInstance: SingletonClass = SingletonClass.getInstance();

This is what we already knew. But what could happen if we try to get a singleton instance inside a Flex module? It could happen that our SingletonClass represents in fact a singleton in two different ways: application-wide singleton or module-wide singleton. In the application-wide case, the instance of SingletonClass is unique across the entire application that uses some Flex modules, while in the module-wide case, the instance in unique only inside a single module, but different across different modules. This is really important to know because we may have undesired behaviors of our application and it could be difficult to figure out what happens without knowing this.

Now, the question is: how do we know when we have an application-wide singleton instead of a module-wide singleton? You may have guessed the answer from the examples links at the beginning of this post. We have an application-wide when the SingletonClass is imported in the main application while we have a module-wide singleton when the SingletonClass is used only inside the modules and never imported in the main application. An example will be useful to clarify everything. Read the rest of this entry »

WP Theme & Icons by N.Design Studio
©2009-2010 Andrea Bresolin. All rights reserved. - Privacy Policy
Entries RSS Comments RSS