00:00
00:00
Newgrounds Background Image Theme

blakenator9872 just joined the crew!

We need you on the team, too.

Support Newgrounds and get tons of perks for just $2.99!

Create a Free Account and then..

Become a Supporter!

As3: Singleton Design Pattern

1,674 Views | 5 Replies
New Topic Respond to this Topic

As3: Singleton Design Pattern 2012-03-19 12:18:06


AS3: Singletons
----------------------
AS3: Main
----------------------
Prerequisite reading: AS3: Static Keyword, The by Diki
----------------------
Source file(s): MySingletonClass.as
----------------------

As previously explained, the static keyword can be used to create properties on objects that only exist once for all instances of that object. But what if we wanted to create an object than only exists once across our ActionScript project?

This is where the singleton design pattern come into play. A singleton is an object that can only be initialised once in your entire project. This is done by creating a static variable the same type of your class and a static function to return that variable:

package  {
	
	public class MySingletonClass {
		
		private static var _this:MySingletonClass;
				
		public function MySingletonClass() {
		
		}
		
		public static function getInstance():MySingletonClass {
     		        if (_this == null){
        		     _this = new MySingletonClass();
      			 }
     		       return _this;
	 	}
	}
}

The above code creates a static variable of type MySingletonClass on the MySingletonClass Object and the getInstance static function returns it. That means where ever we write MySingletonClass.getInstance() it will always return the same MySingletonClass object.

We can then add non static variables and functions to the MySingletonClass, like this:

package  {
	
	import flash.utils.getQualifiedClassName;

	public class MySingletonClass {
		
		private static var _this:MySingletonClass;
		
		private var myVar:String = "Hello World";
		
		public function MySingletonClass() {
			
		}
		
		public static function getInstance():MySingletonClass {
		       if (_this == null){
     		           _this = new MySingletonClass();
     		       }
        		return _this;
		}
		
		public function getVar():String {
			return myVar;
		}
	}
}

This means we can say MySingletonClass.getInstance().getVar() and the output will be "Hello World". We could create a number of non static properties, write getters & setters for them, and using MySingletonClass.getInstance() modify their values.

One small problem at the moment is that we could create new instances of MySingletonClass which would invalidate the singleton design pattern. We can prevent this by adding a simple error check, to see if _this has been initiated, into the constructor:

public function MySingletonClass() {
	if (_this == null) {
		_this = this;
	}else {
		throw new Error(getQualifiedClassName(this) + " is a singleton, use getInstance() instead.");
	}
}

It is important to think long and hard before choosing to use the Singleton design pattern, as it is often over used and used incorrectly. Due to a singleton's global scope it is an easy trap to fall into to want to use it extensively.

Singletons should be used when only one instance of an object is required (i.e. more than one instance of said object would causes errors) and that object needs global scope. I often use a singleton for managing my sounds, as I only want one sound object (as multiple sounds playing over the top of each other would sound bad) and I want to play sounds from anywhere.

There are a number of other design patterns (e.g. Decorator, MVC, etc) all of which have their own pros and cons, the more you have a (at least cursory) knowledge of, the better you'll be able to decide on the right tools for the job.


The water in Majorca don't taste like what it oughta.

| AS3: Main | AS2: Main | Flash Tutorials |

BBS Signature

Response to As3: Singleton Design Pattern 2012-03-19 12:42:06


Trying to wrap my head around this...would a pause menu be a good use of a singleton since there only needs to be one? If not, what are some other examples besides the sound?

Response to As3: Singleton Design Pattern 2012-03-19 12:49:38


Just another way of preventing new instance creation of a singleton using a flag:

public class Singleton {
     private static var creating:Boolean = false;
     private static var instance:Singleton;
     public function Singleton() {
          if (creating) {
          .
          .
          .
          } else {
               throw new Error("Singleton must be used only by getInstance()");
          }
     }
     public static function getIinstance():Singleton {
          if (instance == null) {
               creating = true;
               instance = new Singleton();
               creating = false;
           }
           return instance;
     }
}

Response to As3: Singleton Design Pattern 2012-03-19 16:19:33


At 3 hours ago, MSGhero wrote: Trying to wrap my head around this...would a pause menu be a good use of a singleton since there only needs to be one? If not, what are some other examples besides the sound?

Always pick your tools according to the task you have. Not the other way round.
Design patterns are a powerful tool, if used correctly.

So don't go out and make every object a Singleton just because you only need one of it.
Most often, you will find yourself already implicitly using design patterns if you design your code well.

By all means, do not force one pattern onto a problem.

Response to As3: Singleton Design Pattern 2012-03-19 19:00:05


At 6 hours ago, MSGhero wrote: Trying to wrap my head around this...would a pause menu be a good use of a singleton since there only needs to be one? If not, what are some other examples besides the sound?

Not really. Since a pause menu should just be a specific implementation of a Menu class. And you may end up wanting different pause menus for different parts of the game.
An example would be in a C++ Win32 project. By default, Win32 projects don't have the console (like how a Console Application, does). So, if you wanted to have a console (which is invaluable for real-time debugging) you would create a singleton.

Can't think of a practical example for AS3 though; I've never needed singletons while writing AS3.

Response to As3: Singleton Design Pattern 2012-03-19 19:32:22


At 26 minutes ago, Diki wrote: Can't think of a practical example for AS3 though; I've never needed singletons while writing AS3

As I touched on before, I use a singleton for managing sounds on certain projects due to restraints from the client. Also, while not set up like this, if I'm building something in RobotLegs my Model will be mapped as a singleton ;)


The water in Majorca don't taste like what it oughta.

| AS3: Main | AS2: Main | Flash Tutorials |

BBS Signature