104 | Chapter 3: Singleton Pattern
To create a class, we need a public constructor function within a package. Because
we cannot create a private class within a package, we’ll have to create one outside a
package, and then somehow get it to work inside a package. So, using a single.as
file, the following script first creates a public class, closes the package, and then cre-
ates a private class outside the package. The private class is then called from within
the public class. Example 3-2 shows how this is done.
Save the file asPublicClass.as,and, in an FLA file, type inPublicClassas the Docu-
ment class, and save the FLA file asTestPrivate.fla. When you test the program, you
will see:
This is from a private class
in the Output panel. Notice in Line 8 that the class,PrivateClass, is employed sim-
ply by typing the class name and the method. No constructor statement is used at all.
Creating a Private Class Instance
Keeping in mind the implementation in Example 3-1, we have to work out a way for
the class constructor to act like a private class. If the private class can be part of the
instantiation method (getInstance( )), then we’ll be able to have the same effect as a
private class constructor.
Example 3-2. PublicClass.as
1 package
2 {
3 import flash.display.Sprite;
4 public class PublicClass extends Sprite
5 {
6 public function PublicClass( )
7 {
8 PrivateClass.alert( );
9 }
10 }
11 }
12 //End of Package
13 //**************
14 //Private class
15 class PrivateClass
16 {
17 public function PrivateClass( )
18 {
19
20 public static function alert( ):void
21 {
22 trace("This is from a private class");
23 }
24 }