Game Development Reference
In-Depth Information
the Singleton. The name sort of implies the concept behind it.
A class that is a Singleton will only ever have one instance of itself
in memory and provides a global point of access to that instance.
In the context of a document or top-level class in a site, it ensures
that there is always an easy way to get back to some basic core
functionality. Say, for instance, that all the text for my game is
loaded in from an external XML file because it is being localized
into other languages. I don
twanttoloadtheXMLoverandover
again whenever I need it, so it makes sense for my document
class to be responsible for loading it and then make it available
to all the objects down the display list. The Singleton pattern
provides a good way of doing this because it essentially creates a
global access point from anywhere, even non-DisplayObjects.
However, this is a double-edged sword because abuse of this
pattern to store too much data or rely too heavily on references
back to the main class will break your encapsulation. In practice,
you should never put references to a Singleton class inside an
engine component you intend to re-use as this will make it too
rigid. It should be reserved for classes that are being built for that
specific game. Let
'
s look at an example of a class set up as a
Singleton. This file can be found in the Chapter 5 folder under
SingletonExample.as.
'
package {
import flash.display.MovieClip;
public class SingletonExample extends MovieClip {
static private var _instance:SingletonExample;
public function SingletonExample(se:SingletonEnforcer) {
if (!se) throw new Error("The SingletonExample
class is a Singleton. Access it via the static
getInstance method.");
}
static public function getInstance():SingletonExample {
if (_instance) return _instance;
_instance = new SingletonExample(new
SingletonEnforcer());
return _instance;
}
}
}
internal class SingletonEnforcer {}
Search Nedrilad ::




Custom Search