Quick Tip: The Singleton Pattern
Tutorial Details
- Difficulty: Basix
- Platform: Flash (Flash Player 9+)
- Estimated Completion Time: 10 mins
- Language: AS3
Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Activetuts+. This week’s retro-Active Quick Tip, first published in June 2010, is an introduction to a popular (but commonly mis-used) design pattern.
In this Quick Tip we are going to talk about the Singleton design pattern and how it can help you to optimize your code when you need exactly one instance of a class.
Step 1: Introduction
As a programmer you must be aware that there are some cases where you want to use an instance of a class, but you want to create just one and keep it throughout the entire program. Well, that’s what Singletons are for.
Step 2: What is a Singleton?
A Singleton is a Object-Oriented Design Pattern used by many programmers; it lets you create a sort of “global” instance of a class. It is created in such a way that only one unique instance can exist, so that all instances of that class are in exactly the same state.
Step 3: Why Would We Use it?
The most common example would be a score – for example a football score. You would have a Score class, with properties homeTeamScore and awayTeamScore and a method like increaseScore(team:Team).
Both teams must be able to increase their score when they make a goal, but you can’t give each team their own Score instance; you want both to access and modify the same one.
This is a case where a Singleton is a perfect solution, since it could work as a global instance that anybody can access; you will have just one instance for everyone, so you don’t have to worry that each team will be modifying a different score.
Step 4: Singleton Class
Now let’s start creating a singleton in AS3, but first remember the key elements of a singleton:
- Anyone must be able to access it.
- Just one instance can be created.
Create a new AS3 class and call it Singleton.as.
(Not familiar with class-based coding? Check out this quick intro.)
Here’s the basic Singleton code:
package {
public class Singleton {
private static var instance:Singleton; //This will be the unique instance created by the class
private static var isOkayToCreate:Boolean=false; //This variable will help us to determine whether the instance can be created
public function Singleton() {
//If we can't create an instance, throw an error so no instance is created
if(!isOkayToCreate) throw new Error(this + " is a Singleton. Access using getInstance()");
}
//With this method we will create and access the instance of the method
public static function getInstance():Singleton
{
//If there's no instance, create it
if (!instance)
{
//Allow the creation of the instance, and after it is created, stop any more from being created
isOkayToCreate = true;
instance = new Singleton();
isOkayToCreate = false;
trace("Singleton instance created!");
}
return instance;
}
}
}
Step 5: Create a Flash Project
Now let’s go and test the Singleton, first create a new Flash file named Main.fla. On the properties panel set the class also to Main.

Step 6: Create a Singleton
Create a new class named “Main” and create an instance of Singleton using the constructor:
package
{
import flash.display.MovieClip;
public class Main extends MovieClip
{
public function Main()
{
var testSingleton:Singleton = new Singleton();
}
}
}
Save and run it, you will see that it throws an error telling us to use the getInstance() function instead, so go ahead and do that:
package
{
import flash.display.MovieClip;
public class Main extends MovieClip
{
public function Main()
{
var testSingleton:Singleton = Singleton.getInstance();
}
}
}
Save and run it, there’s no error now, and you can see in the console the text “Singleton instance created!”, meaning that it was created successfully.
So when you use a Singleton class, you cannot use new Singleton(), you have to use Singleton.getInstance() instead.
Step 7: Add Properties to the Class
The Singleton isn’t very useful at the minute. Let’s add a property:
package {
public class Singleton {
private static var instance:Singleton; //This will be the unique instance created by the class
private static var isOkayToCreate:Boolean=false; //This variable will help us to determine whether the instance can be created
//new example property:
public var exampleProperty:String = "This is an example";
public function Singleton() {
//If we can't create an instance, throw an error so no instance is created
if(!isOkayToCreate) throw new Error(this + " is a Singleton. Access using getInstance()");
}
//With this method we will create and access the instance of the method
public static function getInstance():Singleton
{
//If there's no instance, create it
if (!instance)
{
//Allow the creation of the instance, and after it is created, stop any more from being created
isOkayToCreate = true;
instance = new Singleton();
isOkayToCreate = false;
trace("Singleton instance created!");
}
return instance;
}
}
}
Now, in Main.as, you can access testSingleton.exampleProperty just as if it were a normal class. Try tracing it out.
Step 8: Try Creating Another Singleton
To prove that the Singleton does what it’s supposed to do, create another singleton and change the example property of one of them:
package
{
import flash.display.MovieClip;
public class Main extends MovieClip
{
public function Main()
{
var testSingleton:Singleton = Singleton.getInstance();
var anotherSingleton:Singleton = Singleton.getInstance();
anotherSingleton.exampleProperty = "This is set in anotherSingleton";
trace(testSingleton.exampleProperty, anotherSingleton.exampleProperty);
}
}
}
What do you think will happen?
This even works if you create the Singleton variables in different classes.
Conclusion
The singleton pattern can be used on any code, and I highly recommend it if you are going to use just one instance of a class since it gives you better control of it. I hope you liked this Quick Tip, thanks for reading!
Saludos -Eduardo

Now that was good. It’s amazing how much difference it makes, to have a simple, well-written, well laid-out explanation of a design pattern. I already knew how to use it, but this article really simplifies it. Great stuff, Eduardo. :)
Whoa! I’ve never seen anything like that before! Thanks for the tip, it looks really useful!
More about singletons
http://www.gskinner.com/blog/archives/2006/07/as3_singletons.html
I know about the Singleton, but could you give a real life example ?
Could you for instance create a global Resizehandler ?
Well written and nicely explained article love this one. thanks for this one
Thanks Million for this, i already knew about it but this tutorial is so clear!!!
Irie!
In my opinion your implementation is not failsafe. It should be possible to create two different instances of this class with a special amount of luck.
Oh? Interesting…what kind of luck, to be precise?
I am also curious.
Yes that was a really sad comment! However the safety feature has been mentioned by Grant Skinner and a few others in the AS3 community.
Nothing new, but great article. Makes a nice addition to the Active Tuts+ catalouge. :-)
Decent explanation of the Singleton pattern. However, I fail to see the need for the isOkayToCreate flag. Maybe I’m missing something but wouldn’t this be sufficient?
public static function getInstance():Singleton{
if ( instance == null ) instance = new Singleton( );
return instance;
}
One thing I think it is worth mentioning is that the Singleton pattern is considered to be an ‘antipattern’ by a lot of people. It’s still an important concept to understand though.
http://www.as3dp.com/2008/11/26/we-don%E2%80%99t-need-no-stinkin%E2%80%99-singletons-why-to-avoid-the-singleton-pattern-in-actionscript-30-programming/
The flag prevents you from writing something like
var obj:Singleton = new Singleton();
since the constructor is going to throw an error.
This, on some level, mimics a private constructor.
Good point, I never really considered people misusing a Singleton.
I don’t think the flag is necessary.
Couldn’t you make the constructor like this:
public function Model()
{
if (_instance != null)
{
throw new IllegalOperationError(“Use Model.getInstance()”);
}
else
{
initialize();
}
}
I suppose this means one class could construct the Model once. But if anyone else tries to construct it, they would get an error. This still maintains singleton references to the Model.
Wow, after some weeks out i am back here, and i can see the level of the tutorials didnt degraded, very nice work dude.
The singleton comes from another languages that didnt support the static mod keyword, so that was the solution, but nowadays it´s still used even the static mod keyword is supported
Thanks – exellent tutorial and a lifesaver for the applcation I’m developing where we need to access a single customer data set right throughout out all the application components
I would suggest u a better singleton construction, the way i do it in my projects.
package
{
public class Singleton
{
private static var INSTANCE:Singleton;
public static function getInstance():Singleton
{
if(!INSTANCE) INSTANCE = new Singleton(new SingletonKey());
return INSTANCE;
}
public function Singleton(key:SingletonKey = null)
{
if(!key) throw new IllegalOperationError(“Class is singleton”);
}
}
}
internal class SingletonKey { }
Wicked tutorial. So easy to follow, got my score singleton up and running in minutes! Keep up the good work.
Really Great Tutorial!
I’m using a difference approach to protect the Singleton class from beeing instanciated. Instead of a static variable ( private static var isOkayToCreate:Boolean=false ) I’m used to build a little private class inside the SingletonClass, which can’t be instanciated from outside the singleton class.
Here’s a little example of what i mean:
package de.abija.utils
{
// THEORETICAL ABSTRACT STATIC CLASS
public class ProjectValues
{
// EXAMPLE STATIC VARIABLES
public static const SWF_HOLDER_HEIGHT:int = 980;
public static const SWF_HOLDER_WIDTH:int = 1920;
public static const COLOR_BG:uint = 0×003774;
// CONSTUCTOR (cant be private…sad but true)
public function ProjectValues(pvt:PrivateClass)
{
throw new Error(“Never instanziate the ProjectValues Class! It’s an abstract static class which should be used like the Math Class, by calling just ClassMethods and ClassProperties!”);
}
}
}
class PrivateClass
{
// CONSTRUCTOR which only can be instanziated inside the this ProjectValues Class
public function PrivateClass()
{
trace(“building PrivateClass instance”);
}
}
Carefull. This shows not the whole SingletonPattern. It’s just another aproach how to protect a class from beeing instanciated!
@Xander: It’s an real life example about how I’m currently managing my global ProjectValues.
As stated in some comments there are people having issues with this design pattern. There is a problems with the singleton design pattern in Actionscript. You cannot extend them, because you cannot change the return-type of getInstance(). It would be a good idea to mark the class as ‘public final’. Adding new features is hard. It’s hard to debug/test and since it is mostly (over)used as some kind of global state (aka ‘the new _root’). Singletons are not easy to remove, so most singletons keep excisting in memory even when it is not actually needed.
I remember this great line “A singleton today, is a multiple tomorrow” So be aware if you want to create a scalable application.
So.. Singletons should be used with care. They are handy, but should be used with care. Check out google on singletons,
Having inherited projects where other developers overused and abused this pattern, I just want to *strongly* caution against its use unless absolutely necessary. There is a tendency for people to use this pattern, rather than properly separating their application logic. Which means you end up with a lot of this all over the page:
MyGiantManager.getInstance().getSomeOtherManager.doSomething();
It is DANGEROUS code and will bite you in the ass if you’re not careful with it. If you don’t have a strong understanding of MVC, study that first before you start tossing these around everywhere. Otherwise you end up with spaghetti and an application full of globals (which is basically what the Singleton amounts to in most cases)
Wow I never seen anyone professional use this pattern incorrectly!
GoF states “…provide a global point of access to it…”
With that in mind I cant see why anyone would abuse it since, it should only be exposed through the framework API or as GoF states, through a global point.
Example: Assuming Game is a framework in which all game elements live;
var game:Game = new Game(); //inside Game some where A Scores Singleton gets initialized and is stored in a variable. public var score:Score; //use getter instead public function Game()/*constructor*/ { score = Score.getInstance(); } //Accessing the singleton is now done from a single point. game.score.addScore(999999); game.score.getScore();Also that is ok to create isn’t very elagant, why not use an inner class;
So all one would have to say is,
public static function instance():Scores { if(!instance) instance = new Scores(new Key()); return instance; } class Key{}Anyway, I’ve never come across any issues with Singleton.
Why didnt you just use a private constructor as that way enforces a locked access. That ways you wouldnt need the ‘isOkayToCreate’ boolean. That’s how we do it in Java and PHP
Because, unfortunately, in ActionScript 3 constructors can just be public, you can’t simply have a private constructor.
Hi, I am not able to go ahead from STEP 6
I am using below code and still getting the errors
package
{
import flash.display.MovieClip;
public class Main extends MovieClip
{
public function Main()
{
var testSingleton:Singleton = Singleton.getInstance();
}
}
}
Error1:
———
Description: 1046: Type was not found or was not a compile-time constant: Singleton.
Source: var testSingleton:Singleton = Singleton.getInstance();
Error2:
———
Description: 1120: Access of undefined property Singleton.
Source: var testSingleton:Singleton = Singleton.getInstance();
Also, I noticed one more thing for STEP 6 when you describe about getInstance()
check the declaration
“public class Main exends MovieClip”
Make sure you have the Singleton.as file (from Step 4) in the same directory as your FLA.
Thanks for pointing out the “exends” typo; I’ve fixed that now :)
My .as file is in same folder. I have changed the Main.as to Singleton.as
Now I don’t receive any error. But I am not even able to trace anything…
Below is the code for the same…
package
{
import flash.display.MovieClip;
public class Main extends MovieClip
{
public function Main()
{
var testSingleton:Singleton = Singleton.getInstance();
trace(“Hello”);
}
}
}