[MUD-Dev] Singleton design pattern (OT?)

Adam Wiggins adam at angel.com
Tue Aug 31 16:20:43 New Zealand Standard Time 1999


On Tue, 31 Aug 1999, Cynbe ru Taren wrote:
> > Eli Stevens once said:
> > I have been working on the problem of how to best implement the Singleton
> > class [1] from _Design Patterns_, by Gamma, et al. in C++.  I have wasted a
> > lot of time fooling around with this, and now that I have an answer that I
> > think I like, I am going to throw it out in hopes that someone else will be
> > saved a bit of time.  :)
> 
> Last company I worked at (Activerse, a Java outfit) the guys were
> threatening to > strangle the next person to implement a Singleton in
> company code.  Seems like in practice most of them turn out to need multiple
> instances sooner or later, and recoding to allow this is a pain.

I'm pretty neutral on singletons (it always seemed to me that they don't
hold any particular advantage over a global variable), but they are very
popular here at Angel.  We've been using them heavily in our code for
years with nary a complaint.

Of course, it's very simple to create one: thanks to some macros we've long
used, you only need a single line in the class definition:

class foobar
{
   SINGLETON_INTERFACE(foobar);
/* rest of class stuff */
};

And one in the .c file itself:

#include "foobar.h"

SINGLETON_IMPLEMENTATION(foobar);

This implements GetInstance() and related functions.  Then we usually have
a macro for easy access in the .h:

#define FOOBAR foobar::GetInstance()


Generally we use this for all of the basic game "managers", including input,
render, sound, game, AI, and so forth.  So the code ends up looking like
this:


  [ ... ]

  GAME.AddToScore(1000);

  if (INPUT.ButtonPressed(BTN_3))
     /* ... */

  crCreature *cr = AI.FindClosestLivingCreature(pos);

  RENDER.Draw(cr->GetModel(), cr->GetMatrix());


Since they are all just macros, you could always change them to access
something else later anyways.  But we've never needed to.  *shrug*


Adam





_______________________________________________
MUD-Dev maillist  -  MUD-Dev at kanga.nu
http://www.kanga.nu/lists/listinfo/mud-dev



More information about the MUD-Dev mailing list