Singleton

Type of class for when you only ever want one instance to be made of it. It allows any area of code to access data/functions without relying on global variables (global code is instead accessed through the single object instance).

Use when:

Example C++ Code


// the singleton class that will only have one instance
class Singleton
{
public:

    static Singleton *getInstance()
    {
        if (instance == NULL) {
            instance = new Singleton;
        }
        return instance;
    }

private:
    static Singleton *instance;
};

// the instance is stored in this object
Singleton *Singleton::instance = NULL;

// this class will access the singleton
class WorkerClass1
{
public:

    void init()
    {
        // this points to the Singleton::instance above
        singleton_ptr = Singleton::getInstance();
    }

private:
    Singleton *singleton_ptr;
}

// this class also accesses the same singleton
class WorkerClass2
{
public:

    void init()
    {
        // singleton_ptr will access the same object as above in
        // WorkerClass1
        singleton_ptr = Singleton::getInstance();
    }

private:
    Singleton *singleton_ptr;
};