Posts Tagged ‘Design Patterns’

The Art and Beauty of Singletons

Monday, April 14th, 2008

What is a Singleton?

A) In poker, a card that is the only one of its rank.
B) In animal husbandry, the sole surviving offspring of a litter.
C) In astrology, a single planet alone in a hemisphere (or some crap like that).
D) In mathematics, a set with only one member.
E) In England, a small village about 7 miles north of Chichester in West Sussex.

A cute yet tragic Singleton

All of these things share a trait, and that trait is that each is the only one of its kind. If two kittens survive from a litter, neither one is a singleton. If a set has more than one number, it is not a singleton. In works the same way in object-oriented programming; a Singleton is a class that allows only one instance of itself; if there are more than one, that class cannot be a Singleton.

So why would one want a class that only allows one instance of itself? I can think of many applications. A ScoreKeeper class for your game, perhaps, or a Countdown class that keeps track of how much time you have to complete a level. In OS Wars I use a Singleton to keep track of all building resources currently in the game. There’s another one that keeps track of all the units on the battlefield. In fact, the Battlefield itself is a Singleton, because there’s no reason I would ever need more than one.

Another great thing about a Singleton is that, because there is only one, it’s very easy to get to. With a normal object, you have to worry about passing it around to the various classes that might need it. With a Singleton, that’s not necessary. All you need to do is import the class and voilà- there’s your Singleton.

The Village of Singleton

It works this way because the class itself keeps a static reference to the only instance of itself. So instead of calling the constructor to get a reference to a new instance, you call the SingletonClassName.instance method to get a reference to the already-created instance. If that doesn’t make sense, here’s an example. This first piece of code is what a normal ScoreKeeper class would look like. With this structure, you can use that syntax that everyone knows and loves, new ScoreKeeper(), which returns a brand new ScoreKeeper every time it’s called.

package
{
	public class ScoreKeeper
	{
		public function ScoreKeeper()
		{
			trace( "new ScoreKeeper" );
		}
	}
}

But suppose you wanted to ensure that there was only one ScoreKeeper, and you wanted to be able to easily access it from any location in your program. That means two things: A) the constructor can only be called once, and B) you need to keep track of the new ScoreKeeper that one time the constructor does get called. What good is having one instance of a class if you can’t get to it? So here’s the Singleton version of the above class:

package
{
	public class ScoreKeeper
	{
		private static var _instance:ScoreKeeper;
 
		public static function get instance()
		{
			if ( !_instance )
			{
				_instance = new ScoreKeeper();
			}
 
			return _instance;
		}
 
		public function ScoreKeeper()
		{
			trace( "new ScoreKeeper!" );
		}	
	}
}

There are two differences here: the static variable _instance and the static method get instance(). The _instance variable is where the actual instance of this class is stored. And the get instance() method, of course, enables you to access this instance. So to access this Singleton, you would use:

ScoreKeeper.instance;

And to call any methods or properties of the Singleton, you would use this syntax:

ScoreKeeper.instance.addScore( 50 );
trace( ScoreKeeper.instance.score );

This of course assumes that your class has a public method called addScore() and a public property called score. You can get to any public methods or properties this way.

This also adds one more layer, called lazy initialization. Look in the get instance() method, and notice that before it returns a reference to the Singleton, it checks to see if that reference exists. If so, it simply returns it. If not, it creates it first and then returns it. Either way, you’re guaranteed to get the one existing instance.

There is one problem remaining- if you were so inclined, you could still call the constructor without going through get instance(), which would of course result in two Singletons. And as we discussed above, making two of something makes it not a Singleton anymore. So how can we prevent this? There are a few ways I’ve seen floating around, but the simplest is this:

package
{
	public class ScoreKeeper
	{
		private static var _instance:ScoreKeeper;
 
		public static function get instance()
		{
			if ( !_instance )
			{
				_instance = new ScoreKeeper();
			}
 
			return _instance;
		}
 
		public function ScoreKeeper()
		{
			if ( _instance )
			{
				throw new Error( "Singleton already exists- use get instance() to access" );
			} else {
				trace( "new ScoreKeeper!" );
			}
		}	
	}
}

The new lines are in the constructor. The get instance() method still only calls the constructor once, but if you forget it’s a Singleton and call the constructor later, you get a runtime error.

There are also a couple more complicated ways of ensuring that your Singleton is in fact a Singleton, but I haven’t lost too much sleep over over it. I usually even leave out the check in the constructor. Just remember that if it has _instance and get instance(), and a big comment up at the top that says “SINGLETON!”, it’s probably a Singleton.

MXML Singletons in Flex 3

Thursday, April 10th, 2008

If you’re not clear on what a Singleton is, try glancing through my brief yet poignant article here: The Art and Beauty of Singletons.

Creating a Singleton through MXML

Okay, so I’ve been putting together a little image-viewer component in Flex, and I wanted it to load one data model that all other components would share. Sounds like a job for a Singleton, right? However, I also wanted to instantiate said model from MXML, which adds some kinks. In fact, I’ve heard it said that it’s not possible at all. And after some trial and error, I found that apparently it is possible- you just have to hack around a little bit.

If you instantiate your class (or “component”) through MXML, Flex will automatically call its constructor. Typically, this is a bad thing because you don’t call constructors directly in Singletons- instead of calling a method that returns a new object (i.e. a constructor), you call a method that returns a reference to an already-created object (getInstance() or instance()). Flex won’t do that for you. However, this is not a deal-breaker. To make that class a Singleton, you just need to make sure that the constructor is only called once.

So, set up your Singleton like normal:

private static var _instance: DataModel = null;
public static function get instance(): DataModel
{
	return _instance;
}

Then, in the constructor of said Singleton, add the following:

if ( !_instance )
{
	_instance = this;
} else {
	throw new Error( "DataModel is a Singleton: only one instance allowed." );
}

All I’ve done here is move the creation of the Singleton from the get instance() method to the constructor. And if the constructor is called more than once, it throws an error. Now you can instantiate the class through MXML, just like any other component.

<model:DataModel
		id="dataModel"
		xmlURL="fileName.xml" />

Meanwhile in Actionscriptland, you can refer to this instance of your class just like it was a normal Singleton:

	trace( DataModel.instance ); // traces "[object DataModel]"

Plus, if you try to create another instance, be it through MXML or through ActionScript, you’ll get a good ol’ runtime error. You’ll have to wait until runtime to see it, but that’s certainly better than nothing, right?