The Singleton Design Pattern
Often it’s
useful to guarantee that an object is only instantiated once and/or that it is
globally accessible. For example, in game designs that have environments
consisting of many different entity types — players, monsters, projectiles,
plant pots, etc. — there is usually a “manager” object that handles the
creation, deletion, and management of such objects. It is only necessary to have
one instance of this object — a singleton — and it is convenient to make
it globally accessible because many other objects will require access to it.
The
singleton pattern ensures both these qualities. There are many ways of
implementing a singleton (do a search at
google and you’ll see what I
mean). I prefer to use a static method,
Instance, that
returns a pointer to a static instance of the class. Here’s an example:
/* ------------------ MyClass.h -------------------- */ #ifndef MY_SINGLETON #define MY_SINGLETON
class MyClass { private:
// member data int m_iNum;
//constructor is private MyClass(){}
//copy ctor and assignment should be private MyClass(const MyClass &); MyClass& operator=(const MyClass &);
public:
//strictly speaking the destructor of a singleton should be private but some //compilers have problems with this so I’ve left them as public in all the //examples in this article ~MyClass();
//methods int GetVal()const{return m_iNum;}
static MyClass* Instance(); };
#endif
/* -------------------- MyClass.cpp ------------------- */
//this must reside in the cpp file otherwise an instance will be created //for every file in which the header is included MyClass* MyClass::Instance() { static MyClass instance;
return &instance; } |
Member
variables and methods can now be accessed via the Instance method like so:
int num = MyClass::Instance()->GetVal(); |
Because I’m lazy and don’t like writing out all that syntax each
time I want to access a singleton, I usually #define something like this:
#define MyCls MyClass::Instance() |
Using this new syntax I can
simply write:
int num = MyCls->GetVal(); |
Much
easier, don’t you think?
NOTE
If singletons are a new concept
to you, and you decide to search the Internet for further information, you will
discover they fuel many a good argument about the design of object-oriented
software. Oh yes, programmers love to argue about this stuff, and nothing
stokes a dispute better than the discussion of global variables or objects
that masquerade as globals, such as singletons. My own stance on the matter
is to use them wherever I think they provide a convenience and, in my
opinion, do not compromise the design. I recommend you read the arguments for
and against though, and come to your own conclusions. A good starting place is
here: http://c2.com/cgi/wiki?SingletonPattern |