Design Partten: Singleton appliy to Game

A singleton ensure that a class has only one instance and provide a global point of access to it.

There are many ways to create a singleton, here is a way to do it:
//Ok this is the Sound class, a singleton
class Sound
{
protected:
  
static Sound *Instance;
public:
  
static Sound *Inst()
  
{
    
if(Instance==NULL) Instance = new Sound;
    
return Instance;
  }


  
void Init();
  
void PlaySound(int id);
  
void Shutdown();
}
;
Sound 
*Sound::Instance=0;//Set the instance pointer to null


Now here's how you can use your singleton ANYWHERE in your program.
//Let's say this is GameEngine.cpp
void Engine::Init()
{
  Sound::Inst()
->Init();
}

void Engine::DoFrame()
{
  Sound::Inst()
->PlaySound(53);
  
//Do other stuff
  Sound::Inst()->PlaySound(33);
}



You never have to create any object externally since the class will dynamically create the object by itself when calling the static function Inst() for the first time.

The problem right now is that the dynamically created 'Instance' won't be deleted.
I would add a "delete Instance;" in the Shutdown function of the class Sound and make sure to not forget to call it... but I believe there's a better way to delete the instance.
Unfortunatly I rarely use Singletons so I don't really know..

But I suggest you to do some search on google for singletons, there are a lot of info about them...

posted on 2004-07-23 13:17  LeighSword  阅读(342)  评论(0编辑  收藏  举报

导航