O'Reilly logo

ActionScript 3.0 Design Patterns by Chandima Cumaranatunge, William Sanders

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Key OOP Concepts Used with the Singleton Pattern

One of the first issues we need to address is that of using private functions as constructors. In the Singleton pattern implemented in ActionScript 2.0 and Java, the "classic" Singleton is created using a private constructor so that, given the structure of the constructor, only a single instance can be created. Example 3-1 shows a typical implementation:

Example 3-1. Classic Singleton

class Singleton
{
    private static var instance:Singleton;
    private function Singleton()
    {
    }
    public static function getInstance():Singleton
    {
        if (instance == null) {
            Singleton.instance = new Singleton();
        }
        return Singleton.instance;
    }
}

That looks pretty simple. However, looking at it carefully, you'll find a lot going on. Let's go over the key points:

  • Private static instantiation of the instance variable typed as Singleton. The private characteristic of the variable means you can't access it outside the class. Being static means you can access it by the method in the class set up to instantiate a Singleton object.

  • Private class constructor. Example 3-1 is pretty straightforward in ActionScript 2.0. In ActionScript 3.0, we are faced with the dilemma that private functions cannot be used as constructors in packages. Classes to be instantiated need to be public and part of a package. This will be discussed further when creating the equivalent of a private class constructor.

  • Public static function for creating a class instance. The getInstance() method is a wonderfully ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required