102 | Chapter 3: Singleton Pattern
in teamwork, the Singleton can be used to make sure another developer on the team
doesn’t create an instance of the class when you’ve already done so. The Singleton
design pattern tells other developers not to create more than a single instance of the
base class associated with the pattern.
Second, using global variables in no way restricts their usage to a single instance.
They can be instantiated anywhere from a top-level package to within a function
inside a class. Global access must go hand-in-hand with single instantiation.
This is not to say creating a Singleton class is difficult. You can create the class using
a single file, and there’s not a lot of code in the basic class. You can add all the meth-
ods and properties you want, and so a Singleton isn’t restrictive in that sense. The
main issue to wrap your head around is that of making sure only a single instance is
invoked at any one time.
The Singleton Model
Looking at the Singleton structure in the class diagram notation, we see no abstract
classes or interfaces. A key point to note is the use of astati cInstan ce( )and the
connection to the implementation pseudocode. As you will see, the pattern uses
static class variables and methods for the global implementation and the uniqueness
of the instantiation of the class. Figure 3-1 shows this simple but powerful structure.
To move from the diagram structure to a working model, we need to get a couple of
OOP issues straightened out using ActionScript 3.0. Primarily, we need to work out
how to get a self-instantiated class set up. With most of the other patterns, the differ-
ent parts work together with one part implementing or extending the other. So we
need to take a look at the basics.
Key OOP Concepts Used with the Singleton Pattern
One of the first issues we need to address is that of using private functions as con-
structors. In the Singleton pattern implemented in ActionScript 2.0 and Java, the
“classic” Singleton is created using a private constructor so that, given the structure
of the constructor, only a single instance can be created. Example 3-1 shows a typi-
cal implementation:
Figure 3-1. Singleton structure
Singleton
static Instance()
SingletonOperation()
GetSingletonData()
static uniqueInstance
singletonData
return uniqueinstance