Customizable Navigation Bar

Saturday, February 12, 2011

Proper Design Patterns Part 1: Singletons

Now, before we get started, follow me on twitter at http://twitter.com/#!/purdyjo, that way you'll know exactly when new posts are up. They are weekly, but I might throw in a few here and there just to keep you on your toes.

This is going to be the first of a few posts based on design patterns and their uses. A lot of programmers forget these simple programming methods, and it makes their lives that much harder.

The first pattern that I am going to talk about is the Singleton pattern. What is a Singleton anyways? Why would we use them? Why is this way better in certain situations? I will answer all of these questions and more providing you with examples and a piece by piece walk-through on how to build a simple Singleton to get the job done.


So what is a Singleton? You could consider a Singleton a manager class for your game/application, and some applications themselves are Singletons. A Singleton is a class or object, that only has one instance. There can never be more than one instance of this class/object at any time while the program is running, and if you try to create a new one, an error is thrown. 

Now why would we use them? Well, lets say you have a class that does something that multiple classes will need to do, but it has too much extra functionality to extend from, so an Audio Manager could be used as an example here. Now what you could do, is have a sound attached to each individual object, and let them take care of this on their own. It works, it gets the job done. One problem: Not everyone one programs as intelligently as you do, and pointers don't exist in all languages. Now each new object is storing a new sound effect, but that sound effect is already in memory say, 20 times for the 20 objects in the world. Do you see where I am going with this. If you created a Singleton Audio Manager class, you could just have the sound effects stored once, and each class could access a static instance of your Audio Manager class to do what it has to. Less memory required, win!

Awesome, so how do I make one? It's simple really. It is one of the most basic design patterns to follow.
Now what I am going to do is show you step by step the simplest way to create a Singleton class in C++, and then I will show you how to create one in Actionscript 3.0, because Actionscript at this point does not allow us to do it the same way.

Alright so C++

class SingletonExample
{
private:
         static  SingletonExample mInstance;

Whoa whoa whoa, why do we have a variable of its own type? and why is it static? 
This is part of what makes this class a singleton. Having a variable of its own type stops us from having to create a friend class(if your language of choice allows) to handle creating the single instance. The variable being static allows us to return the instance from a static function that you will see if you keep scrolling.

          SingletonExample()
         {
         }

Alright, so what is going on here? Why is the constructor private? If we want this class to be a singleton class, what we need to do is make sure that this class handles the creation of itself. If other classes can instantiate a new one, then there was no real point to creating the singleton class. 

public:
        static SingletonExample getInstance()
        {
                if(mInstance == NULL)
                {
                         mInstance = new SingletonExample();
                 }

                return mInstance;
        }
};

Are you starting to get it now? We use a static function called getInstance to return the single instance of this object. Within this function we check to see if the instance already exists. If it doesn't, we create a new one, and then we return the instance to whatever class called this function.

That is honestly it to get a singleton class started in C++, and this can be applied to almost any language. 

Now Actionscript 3.0. For this one, I am just going to right out the entire class, and then go through the differences once it's finished.

package
{
        public class Singleton //extends MovieClip if you only want one instance of the player for example
        {
                static private mInstance:Singleton = new Singleton();
                public function Singleton()
                {
                        if(mInstance != null)
                        {
                                throw new Error("Error: Cannot create new instance of Singleton Class. Use getInstance instead.");
                        }
                }

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

Alright, so I assume that you can see the difference here. Actionscript does not support private constructors, so we need to create a workaround for this. So what we do is call the constructor as soon as we declare the static instance of the object, and within the constructor we check to see if the instance already exists or not. Other than that the class works basically the same.

So this is the end of this post, I'll have more like this soon enough, expect a post at least every Saturday. More updates on my games and current projects will also make it here. 

Have a good one, and learn some Assembly, it will make you a better programmer!