Creating a Singleton class in AS3 is quite straight forward. You can use a static property coupled with a static method and an enforcer class to do so. Static methods/properties are those which can be accessed even before an instance of the class exists (evaluates at compile time as opposed to run time). For example the Math class. You do not need to initialize the Math class to get round(), ceil() or a floor() of a floating point number.
The score of a game is a great example for a Singleton class. Create a as file called Score.as and paste the following in it:
package
{
public class Score
{
private static var _instance:Score = null;
public function Score(enf:Enforcer)
{
}
public static function get_instance():Score //static method-> accessed directly without any instance
{
if(_instance == null)
{
_instance = new Score(new Enforcer); //new Enforcer makes sense only in this line
}
return _instance; //returns the same Score object no matter what
}
}
}
class Enforcer
{
//empty class -> useable from this file only
}
The Enforcer class is outside the package and hence can be accessed by this .AS file only. Our Score class needs this class as an argument and it cannot create one by
var obj:Score = new Score(); //no argument – will throw an error
var obj:Score = new Score(new Enforcer()); //doesnt recognize Enforcer out of context
Only the public static method get_instance() returns the single Score class by directly checking the static property _instance.
To make this class a little more useful we ll add a actual score property and getter & setter methods to use the actual score.
Add the colored items to the Score class
package
{
public class Score
{
private static var _instance:Score = null;
private var _the_score:Number = 0;
public function Score(enf:Enforcer)
{
}
public static function get_instance():Score
{
if(_instance == null)
{
_instance = new Score(new Enforcer);
}
return _instance;
}
public function get score()
{
return _the_score;
}
public function set score(num:Number):void
{
_the_score = num;
}
}
}
class Enforcer
{
}
Now create a new Flash file(AS3) and save it in the same place as the Score.as file and paste the following in the first frame
var obj = Score.get_instance();
trace(obj.score); //returns 0
var obj2 = Score.get_instance();
trace(obj2.score); //returns 0
obj2.score=20; //changing the score from the second Score object
trace(obj.score); //accessing the first obj’s score, returns 20