108 | Chapter 3: Singleton Pattern
So what does this mean? Essentially, the compiler does not recognize the class
namedPrivateClass,and doesn’t think you remembered to create it, or that you
don’t have an adequate path to it. However, that’s not the problem. The problem is
that it’s a private class, and cannot be accessed except through the class you’re try-
ing to instantiate—the Singleton class.
A Singleton Instantiation Method
In developing the Singleton class, we had to include a special method in the con-
structor to instantiate the class. As you’ve seen, the standard methods used to create
a class instance just don’t work. ThegetInstance( )function solves the instantiation
problem. The following code segment shows this essential part of the program,
which allows access to the private class necessary for the instantiation of the class:
public static function getInstance( ):Singleton
{
if(Singleton._instance == null)
{
Singleton._instance=new Singleton(new PrivateClass( ));
trace("Singleton instantiated");
}
............
return Singleton._instance
}
The_instancevariable is a private static one that will hold an instance of the Single-
ton class. Because we want only one instance, the code checks to see if there’s an
instance already. Any ActionScript 3.0 user-defined class data type that has not been
assigned a value isnullby default. So after making sure thatSingleton._instanceis
null(no other instance exists), the script creates one. Here we see the instantiation
line we tried outside of the class:
....new Singleton(new PrivateClass( ));
This is possible because thePrivateClassis referenced from within the Singleton
class.
Figure 3-3. Compiler not finding class