Advertisement

Singleton

Started by May 16, 2001 11:16 AM
0 comments, last by pax 23 years, 8 months ago
I mentioned singletons in a previous post and thought I should clarify what that is. This is as good a place as any. A singleton class is a class for which there is only one instance. This is enforced by hiding the constructors and exposing a class method for retrieving a reference to the instance. For example (C++):

class Singleton
{
public:
    static Singleton *GetSingleton()
    {
        if (instance == NULL) instance = new Singleton();
        ref++;
        return instance;
    }
    static void ReleaseSingleton(Singleton *s)
    {
        if (s == instance) ref--;
        if (ref == 0)
        { delete instance; instance = NULL; }
    }

private:
    Singleton();

    static Singleton *instance = NULL;
    static int ref = 0;
};
 
Because the constructor is private, only the Singleton class can create instances of the Singleton class. This example also uses reference counting, which is a good way of checking for and preventing memory leaks (common in dynamically allocated static members). Topic for discussion: Where would you use singletons? p
p
Wherever you only want one instance of a particular class. You could use it for the application class, engine class, graphics class, input class, sound class, any pure factory classes, timer class, etc.

Just be careful tho, as discussed in a previous thread in this forum, there is no elegant way to derive a class from a singleton class. This could potentially hurt reusability.


- Houdini
- Houdini

This topic is closed to new replies.

Advertisement