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.

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.

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

<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].