106 | Chapter 3: Singleton Pattern
Save the files asSingleton.as. You now have a Singleton to work with. The next step
is actually using it.
Instantiation with a Private Class Parameter
When the Singleton class is instantiated as an object in a program, you cannot suc-
cessfully use the following format:
var mySingleton:Singleton = new Singleton( );
This format runs into the ironic problem of needing an argument in the constructor.
Right now, the declaration line has 0 arguments, and you need 1. The argument you
need is a reference to a private class that can be accessed only through the public
class you’re trying to instantiate. (There’s a parado xif there ever was one!) Look at
Example 3-5 for a bad implementation of the Singleton class:
Example 3-4. Singleton.as
package
{
public class Singleton
{
private static var _instance:Singleton;
public function Singleton(pvt:PrivateClass) {
}
public static function getInstance( ):Singleton
{
if(Singleton._instance == null)
{
Singleton._instance=new Singleton(new PrivateClass( ));
trace("Singleton instantiated");
}
else
{
trace("Sorry--already have a Singleton instantiated")
}
return Singleton._instance;
}
}
}
class PrivateClass
{
public function PrivateClass( ) {
trace("Private class is up");
}
}
Example 3-5. BadImplementation.as
package
{
import flash.display.Sprite
public class BadImplementation extends Sprite