10.12.2012 Views

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

This second Singleton has getter and setter methods. If we attempt to create two different<br />

instances using two different object names and set different string values to the<br />

_msg variable, we should see only one when we ask for the value, if both use the get<br />

method after the second one has set a different value than the first. That is, we can<br />

have as many names associated with one instance as we want, and they’ll all function.<br />

However, they’ll be referencing only one Singleton instance. The following<br />

pseudocode shows the logic:<br />

• Label A instantiates a Singleton (succeeds).<br />

• Label A uses the set method to add “Message A” (succeeds).<br />

• Label B instantiates a Singleton (Returns the currently instantiated instance).<br />

• Label B uses the set method to add “Message B” (succeeds).<br />

• Label A uses the get method to display the most recently set image. (What will<br />

appear?)<br />

To resolve this issue, open a new <strong>ActionScript</strong> file and add the code shown in<br />

Example 3-9.<br />

Example 3-9. SingletonTest.as<br />

package<br />

{<br />

import flash.display.Sprite;<br />

public class SingletonTest extends Sprite {<br />

public function SingletonTest( ) {<br />

}<br />

}<br />

}<br />

var firstSingleton:Singleton = Singleton.getInstance( );<br />

firstSingleton.setMsg("Singleton instance: firstSingleton");<br />

var secondSingleton:Singleton = Singleton.getInstance( );<br />

secondSingleton.setMsg("Singleton instance: secondSingleton");<br />

trace(firstSingleton.getMsg( ));<br />

trace(secondSingleton.getMsg( ));<br />

Save the file as SingletonTest.as in the same folder as the new Singleton.as file. Open a<br />

new Flash document, type in SingletonText in the Class document window, and save<br />

the FLA file in the same folder as the two <strong>ActionScript</strong> (.as) files. When you test the<br />

movie, your output window shows that only a single instance exists as in Figure 3-5.<br />

It’s clear from the output that only a single instance was created, which must have<br />

been the first one because of the code structure. However, both the instance labels<br />

(firstSingleton and secondSingleton) typed as Singleton data are returning the value<br />

of the second instance. Both instance labels will always have the same value because<br />

they are merely references to the instance, and not actually instances themselves.<br />

Minimalist Abstract Singleton | 111

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!