Design Patterns in ActionScript-Singleton

Single-Seater-Djinn-Chair-128x128 In our real world, many things are one and only. For example, there is only one god in our world, and only one president in the USA, eh, I mean the current president. One and only is very important to our world, and so does to our program.

In some case, we may only need one instance of some classes. If you have any experience on developing the GUI application, you can feel it. For example, there’s only one display object in J2ME application, and only one form in windows application. During those situations, we need to control the number of the class, and it was forbidden that using the new operator to generate a new instance. Further more, we need to supply an interface for accessing the one and only instance.

That’s all about the singleton pattern. And the intent defined by GOF is as follows.

Ensure a class only has one instance, and provide a global point of access to it.

–By GOF BOOK

Now, we come to the operation layer.

In general, we will meet two problems here, one is when to initialize the instance and the other is how to ensure thread-safe in the multithread environment. Because Action Script 3 doesn’t support multithread, so we don’t need to care the thread-safe.

Before we solve the first problem, we need to provide a global access point for getting the instance. Of course, we don’t except the users use the new operator to get a new instance. Maybe we could change the constructor modifier from public to private. Eh, if you really do so, you’ll get a complier error, because in Action Script 3, the modifier of a constructor can only be public. So, we need to change our method.

If we can’t change the modifier, the constructor can be called outside. One solution is we can throw an error in the constructor, just like below.

public function President()
{
if(president != null)
throw new Error(“You shouldn’t use the new operator!”);
}

If there is already have an instance, we need to throw an error. If not, let it go, and then we can get an instance.

This is not a good way, but it works :) . Now, let’s come to the first problem. In general, there will be two kinds solution. One is called early initialization, the other is lazy initialization. The first one initializes the instance when the program first runs, and the other initializes the instance when the getInstance () method called.

The code below shows early initialization. The instance will get initialized when the class gets initialized.

static var president:President = new President();
public static function getInstance():President
{
return president;
}

The code below shows lazy initialization. As you see, after the getInstance() method was called, the instance will get initialized.

static var president:President = null;

public static function getInstance():President
{
if(president == null)
president = new President();
return president;
}

Which way should be taken depends on your demand. Actually, you’ll need to consider these two situations only when you using this pattern to get a big object in the memory limit environment.

You can download the full source code from download here.

Enjoy!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Reddit
  • Technorati
  • StumbleUpon
  • Twitter
RSS Enjoy this Post? Subscribe to Ntt.cc

RSS Feed   RSS Feed     Email Feed  Email Feed Follow us Follow us
You can leave a response, or trackback from your own site.

5 Responses to “Design Patterns in ActionScript-Singleton”

  1. Steven says:

    Actually, you are forgetting a very common method for creating a Singleton pattern in Actionscript and that is the use of a private SingletonBlocker class that will be the parameter of the constructor, os it cannot be constructed from outside the class.

    Code would be as follows:
    public function Singleton(sb:SingletonBlocker) {};

    public function getInstance():Singleton {
    if(instance == null) {
    instance = new Singleton(new SingletonBlocker());
    }
    return instance;
    }

    and outside the class you would get:
    internal class SingletonBlocker {} ;

    So, this will in effect stop you from being able to create a Singleton directly

  2. Nathan Levesque says:

    This is the same method I use. I don’t particularly see the benefit of using a private class as a constructor parameter. I would rather work with developers educated enough to know better.

  3. Steven says:

    Hmm, an benefit… Ow, I don’t know. Maybe the small matter of compile time checking. With your method you only get runtime errors, so you could possibly write thousands of lines of code that you think will work, but only when you run it, you will get an error.

    I, on the other hand, can’t even compile the code and know exactly what is wrong and where the error resides within the code. Buggy code shouldn’t compile !

  4. Nathan Levesque says:

    Steven, what if you ever wanted to extend that singleton? I guess my point is if a programmer is instantiating classes so willy-nilly without an understanding that the class is Singleton, than no doubt he’s going to run into problems. I would concede that maybe for library code that would be a requirement, but for me at least that method has too many limitations and I’d rather place the onus on the programmer to code responsibly.

  5. peter says:

    singleton is so stupid… its hyped like HITLER. ctrl+A+del is what i do to the singletons and replace them with static functions then i have one object which is a class.

Leave a Reply