EasyManua.ls Logo

MACROMEDIA FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH - Page 253

MACROMEDIA FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH
830 pages
Print Icon
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
About working with custom classes in an application 253
To use the Singleton design pattern:
1. Select File > New and then select ActionScript File. Save the document as Singleton.as.
2. Type the following ActionScript code into the Script window:
/**
Singleton class
author: John Doe
version: 0.53
modified: 6/24/2008
copyright: Macromedia, Inc.
*/
class Singleton {
private static var instance:Singleton = null;
public function trackChanges():Void {
trace("tracking changes.");
}
public static function getInstance():Singleton {
if (Singleton.instance == null) {
trace("creating new Singleton.");
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
}
3.
Save the Singleton.as document.
4. Select File > New and then select Flash Document to create a new FLA file, and save it as
singleton_test.fla in the same directory as you saved the Singleton class file.
5. Type the following ActionScript code into Frame 1 of the Timeline:
Singleton.getInstance().trackChanges(); // tracking changes.
var s:Singleton = Singleton.getInstance(); // tracking changes.
s.trackChanges();
6.
Save the Flash document.
7. Select Control > Test Movie to test the document.
The Singleton object is not created until you need it—that is, until some other code asks for it
by calling the
getInstance() method. This is typically called lazy creation, and it can help
make your code more efficient in many circumstances.

Table of Contents

Related product manuals