User Guide

Instance and class members 265
Often there are situations when you need exactly one object of a particular type in a system. For
example, in a chess game, there is only one chessboard, and in a country, there is only one capitol
city. Even though there is only one object, it is attractive to encapsulate the functionality of this
object in a class. However, you might need to manage and access the one instance of that object.
Using a global variable is one way to do this, but global variables are often not desirable. A better
approach is to make the class manage the single instance of the object itself using class members,
such as the following example:
class Singleton {
private var instance:Singleton = null;
public function doSomething():Void {
//...
}
public static function getInstance():Singleton {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
The Singleton object can then be accessed using Singleton.getInstance();
This also means that the Singleton object is not created until it is actually needed—that is, until
some other code asks for it by calling the
getInstance method. This is typically called lazy
creation and can help code efficiency in many circumstances.
Using class members: a simple example
One use of class (static) members is to maintain state information about a class and its instances.
For example, suppose you want to keep track of the number of instances that have been created
from a particular class. An easy way to do this is to use a class property thats incremented each
time a new instance is created.
In the following example, you’ll create a class called Widget that defines a single, static instance
counter named
widgetCount. Each time a new instance of the class is created, the value of
widgetCount is incremented by 1 and the current value of widgetCount is displayed in the
Output panel.
To create an instance counter using a class variable:
1.
Create a new ActionScript (AS) file.
2.
Add the following code to the file:
class Widget {
static var widgetCount:Number = 0; // initialize class variable
function Widget() {
trace("Creating widget #" + widgetCount);
widgetCount++;
}
}