Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

Version 1 (modified by landauf, 17 years ago) (diff)

Singleton

Description

The singleton? is an important design-pattern in advanced c++ coding. A singleton is a class, that allows only one existing instance at a time. This is achieved by overloading the constructor as a private function and the implementation of a static funciton that returns a pointer to the only existing instance (or creates the instance if it's not already existing). The pointer itself is stored in a static variable. This variable must be statically set to zero before you access the singleton? the first time.

This way you can retrieve a pointer to the singleton? and access its member functions everywhere in the code without using ugly static objects or completely static classes.

Example

class SlaveSingleton
{
  public:
    static SlaveSingleton* getSingleton()
    {
      if (!pointer_s)
        pointer_s = new SlaveSingleton();

      return pointer_s;
    }

    void sendToWork()
      { this->motivation_--; }

    void bash()
      { this->health_ -= 10; this->motivation_++; }

    void feed()
      { this->health_ += 5; }      

  private:
    SlaveSingleton() : health_(100), motivation_(0)
      { std::cout << "The slave is born." << std::endl; }

    SlaveSingleton* pointer_s;
    int health_;
    int motivation_;
};

SlaveSingleton* SlaveSingleton::pointer_s = 0;
SlaveSingleton::getSingleton()->bash();
SlaveSingleton::getSingleton()->sendToWork();