Additional Blogs by Members
cancel
Showing results for 
Search instead for 
Did you mean: 
abesh
Contributor
0 Kudos
[Cross Posted on http://blog.abesh.net/2008/07/27/singleton-classes-in-actionscript-30/]

 

Singleton Classes are based on the Singleton Design Pattern and have a single instance of the class throughout the  application.  When would one need a singleton class ? A simple example would be a database manager class which would instantiate a connection to the database at the application initialization and have methods for data manipulation of the database tables. In such a case multiple instances of this class is not required and will end up consuming memory and other issues.

How does one implement a Singleton Class ?

Recommended Way

              
  1. Declare a private variable of the type of the same singleton class inside it.
  2.           
  3. Declare a private or protected constructor to prevent the initiation of the class
  4.           
  5. Implement a public getInstance() method which will instantiate  the  variable declared in step 1 if  it has not been instantiated, otherwise return the variable.

Pseudocode

 Class Singleton{
private variable SingletonInstance type Singleton ;
private/protected Constructor(){
//not implemented
}
public function getInstance(){
if (SingletonInstance == null) then{
Instantiate SingletonInstance;
}
return SingletonInstance;
}
}

The next obvious question, which is also the premise of this blog, is how does one implement a Singleton class in actionscript. Well, Actionscript 3.0 does not allow private or protected constructors thus leaving a lot of scope for experimentation and the quest for the perfect implementation, as this Google Search results with the words "singleton classes + actionscript" retruns quite a few implementation variations.

The one that I used for my implementation was sort of inspired by Andrew Trice's Singleton in AS3 example.

package
{
public class Singleton
{
private static var singleton : Singleton

public static function getInstance() : Singleton
{
if ( singleton == null )
singleton = new Singleton( arguments.callee );
return singleton;
}
//NOTE: AS3 does not allow for private or protected constructors
public function Singleton( caller : Function = null )
{
if( caller != Singleton.getInstance )
throw new Error ("Singleton is a singleton class, use getInstance() instead");
if ( Singleton.singleton != null )
throw new Error( "Only one Singleton instance should be instantiated" );
//put instantiation code here
}
}
}

Have you come across a better Singleton Implementation ? I would definitely want to learn 🙂

2 Comments