« Language Overload | ^ Main | Using Yahoo! Maps GeoCoding API in C# »


What is a Singleton?

A Singleton is an OOP pattern which is pretty sweet for several situations. Take for instance you have a data class that pulls web service data (which is what I'll be doing when I finish this post). Well, you don't necessarily want all of your other classes to have to create a new instance of the data class, set the necessary parameters, then make the call. Instead, create a Singleton, do it once, and in your classes create a reference to the instance.

I still haven't answered what a Singleton is. Ok...it's an OO pattern. That's coo but the underlying architecture is the sweet spot. Let's look at the code below.

This is a typical Flash class. I put comments around the Singleton specific code. To give a definition, a Singleton class insures one and only one instance will ever exist in the application. Instead of doing


var me:Data = new Data();

you would do

var me:Data = Data.instance;

Essentially you would have an isntance of the class. Let's review the code a little further.

Notice the constructor is deemed private. This way anyone who calls new Data() will get an error ("The member is private and cannot be accessed."). Everything about your class will stay the same except for the Singleton portion. Notice there is a public variable called test. Once you have an instance you interact with it as you normally would. The Singleton methods/variables are all static, and this is a requirement. Let's see how you use it.

import Data;

var myData:Data = Data.instance;
trace(myData.test); //traces: 0

This is the exact code that will cause an error:

var myData:Data = new Data(); //compiler error, as shown above

As you see in the instance() getter method we simply return _instance, which is a private static variable, but first we check to see if _instance is defined. If it isn't defined we create it by calling Data(). That's right, the static method calls the constructor by creating a new instance of itself, essentially.

You will learn more about Singleton's by toying with them. In what I'm doing right now I basically want one class to retrieve/hold some data. I can import this class into 100 classes and call Data.instance 100 times but only 1 instance of the Data class will exist in the app.

Peep the code and feel free to use it.

class Data{
/* start Singleton Specific */
private static var _instance:Data;

public static function get instance(){
if(_instance == undefined) _instance = new Data();
return _instance;
}
/* end Singleton Specific */

public var test:Number = 0;
private function Data(){
trace("instance created");
}

public function toString(){
return "Data";
}
}

Posted by John C. Bland II on January 26, 2006 1:23 AM |

TrackBack

TrackBack URL for this entry:
http://mt.katapultmedia.com/mt-tb.cgi/14

Post a comment