ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Minimalist Abstract Singleton | 109

Now, we can write a class that instantiates the Singleton class. Open a new Action-


Script file, and enter the code shown in Example 3-7. The script attempts to instanti-


ate two instances of the Singleton class. If the class is set up correctly, it’ll allow you


only one instance.


Save the file asSingletonTest.as, open a new Flash document, and typeSingletonTest


in the Document class window. Both files should be saved in the same directory as


theSingleton.asfile. Now test the application in the Flash document. Figure 3-4


shows what you should see:


The fact that you can see the message, “Sorry--already have a Singleton instantiated”


means that only one of the two instances was successfully created. That’s exactly


what we were hoping for. Had both instances been created successfully, we’d have to


go back to the drawing board. However, after the first one was created, as indicated


by the messages, “Private class is up” and “Singleton instantiated,” the second one


was blocked.


One Instance and Different References


In reviewing the classic Singleton design pattern application, you may have noticed


that no matter what happens during an attempted instantiation of the class, the pro-


gram always passes through to a statement that returns aSingleton._instance.We


know that if the conditional statement finds that aSingleton._instanceexists, it


doesn’t create another one, but still returns whatever instance has been instantiated.


Example 3-7. Instantiating Singleton class


package
{
import flash.display.Sprite;
public class SingletonTest extends Sprite {
public function SingletonTest( ) {
var firstSingleton:Singleton = Singleton.getInstance( );
var secondSingleton:Singleton=Singleton.getInstance( );
}
}
}


Figure 3-4. Single class instance created

Free download pdf