Minimalist Abstract Singleton | 111
This second Singleton has getter and setter methods. If we attempt to create two dif-
ferent instances using two different object names and set different string values to the
_msgvariable, we should see only one when we ask for the value, if both use the get
method after the second one has set a different value than the first. That is, we can
have as many names associated with one instance as we want, and they’ll all func-
tion. However, they’ll be referencing only one Singleton instance. The following
pseudocode shows the logic:
- Label A instantiates a Singleton (succeeds).
- Label A uses the set method to add “Message A” (succeeds).
- Label B instantiates a Singleton (Returns the currently instantiated instance).
- Label B uses the set method to add “Message B” (succeeds).
- Label A uses the get method to display the most recently set image. (What will
appear?)
To resolve this issue, open a new ActionScript file and add the code shown in
Example 3-9.
Save the file asSingletonTest.asin the same folder as the newSingleton.asfile. Open a
new Flash document, type inSingletonTextin the Class document window, and save
the FLA file in the same folder as the two ActionScript (.as) files. When you test the
movie, your output window shows that only a single instance exists as in Figure 3-5.
It’s clear from the output that only a single instance was created, which must have
been the first one because of the code structure. However, both the instance labels
(firstSingletonandsecondSingleton) typed as Singleton data are returning the value
of the second instance. Both instance labels will always have the same value because
they are merely references to the instance, and not actually instances themselves.
Example 3-9. SingletonTest.as
package
{
import flash.display.Sprite;
public class SingletonTest extends Sprite {
public function SingletonTest( ) {
var firstSingleton:Singleton = Singleton.getInstance( );
firstSingleton.setMsg("Singleton instance: firstSingleton");
var secondSingleton:Singleton = Singleton.getInstance( );
secondSingleton.setMsg("Singleton instance: secondSingleton");
trace(firstSingleton.getMsg( ));
trace(secondSingleton.getMsg( ));
}
}
}