Game Development Reference
In-Depth Information
Traditionally in other languages, a Singleton class would have
a private constructor function, preventing you from calling it.
However, in AS3, all constructors must be public, so we have to put
in an error check to enforce proper use. The class keeps a static refer-
ence to its only instance, and the static getInstance method returns it.
To prevent someone from arbitrarily instantiating the class, we create
a secondary private class that is only accessibly to the main docu-
ment. Think of it like the secret password for the Singleton
scon-
structor. Only the getInstance method knows how to properly create
a new SingletonExample instance as it will fail without this private
class. This is a pretty commonly accepted way of dealing with basic
Singleton classes in AS3. However, this particular example will also
break when used as a document class. This is because Flash will
automatically try to instantiate the class to create the display list hier-
archy. To get this, we must modify the time of instantiation, alter the
way the constructor works, and eliminate the private class. This new
version can be found in SingletonExampleDocument.as.
'
package {
import flash.display.MovieClip;
public class SingletonExampleDocument extends MovieClip {
static private var _instance:SingletonExampleDocument;
public function SingletonExampleDocument() {
if (_instance) throw new Error("This class is a
Singleton. Access it via the static
SingletonExampleDocument.getInstance method.");
_instance = this;
addEventListener(Event.REMOVED_FROM_STAGE, onRemove,
false, 0, true);
}
private function onRemove(e:Event):void {
_instance = null;
}
static public function getInstance():SingletonExample-
Document {
if (_instance) return _instance;
_instance = new SingletonExampleDocument();
return _instance;
}
}
}
Search Nedrilad ::




Custom Search