ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Key OOP Concepts Used with the Singleton Pattern | 103

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 construc-
tors in packages. Classes to be instantiated need to be public and part of a pack-
age. This will be discussed further when creating the equivalent of a private class
constructor.

Public static function for creating a class instance


ThegetInstance( )method is a wonderfully simple function. It checks to see if
an instance has been created, and, if it hasn’t, then it creates one. Otherwise it
simply returns the existing Singleton instance.

The simplicity of the Singleton is clearer after seeing how it actually works in a con-


crete example. However, working with ActionScript 3.0, we’re stuck because we


can’t create a private class constructor. This next section provides a workaround to


this dilemma.


Creating and Using a Private Class Constructor


Rather than showing how your code will fail if you attempt to create a private con-


structor function inside a package, you’re going to see how to effectively make your


very own private class, and use it as a constructor. In fact, you will see how to imple-


ment it in a script.


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;
}
}

Free download pdf