Hello! It looks like you don't have a recent version of Flash Player installed, please download the latest version from http://get.adobe.com/flashplayer/

AS3 Singleton Class

The Singleton class, coded in AS3, is designed to restrict instantiation of a class to only one object. It's good when you only want one object across the whole of your application. An example could be you load in a load of xml data and you want to store the values of the xml for use throughout the application. In AS3 we can write a Singleton Class in the following way. We use the getInstance() to return the object created.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.howtocode
{
[Bindable]
public class Singleton
{
 
/** Only one instance of the model locator **/
 
private static var instance:Singleton = new Singleton();
 
/** Bindable Data **/
 
public var flexData:String = "SuperApp";
public var userScore:int = 0;
 
public function Singleton()
{
if(instance)
{
throw new Error ("We cannot create a new instance.
 Please use Singleton.getInstance()"
);

}
}
 
public static function getInstance():Singleton
{
return instance;
}
}
}

AS3 Singleton Class Access

To access a variable from the Singleton class we use the following.

 

1
2
3
4
5
6
7
8
9
import com.howtocode.Singleton;
 
private var model:Singleton = Singleton.getInstance();
 
// To retrieve flexData String from Singleton Class use model.flexData
trace(model.flexData);
 
// To set flexData String in Singleton Class use the following
model.flexData = "FlexApp"

 

You can of course do something really cool which is place something like place

 

1
<mx:Button id="flexButton" label="{model.flexData}">

 

into you're MXML and when flexData is changed in your Singleton Class it automatically updates you're MXML as we've set the whole Singleton Class as [bindable].