The singleton design pattern

One of the many design patterns mentioned in the book Design Patterns, the singleton is a means of controlling the access to, or the instantiation of, an object for which the number of instances must be strictly controlled at runtime.

Using a singleton, static methods within the code can decide whether an object has been, or should now be instantiated. This is very useful when one type of object may or may not exist and is needed, for example, a file manager...

START FileManager.h

  class FileManager {
  public:
    static FileManager *Instance();
    void ShredFile(char *FileName);

    // destructor - anyone may delete us, the only requirement is that this is called
    //    at least once after instance is called to prevent memory leaks.
    ~FileManager();

    // other file manager member functions    
  private:
    // Instance pointer - the project wide instance of file manager.
    static sm_FileManager *_instance = NULL;

    // constructor - prevents other classes from making new FileManagers
    FileManager();

    // other file manager member functions
  }

END

START FileManager.cpp

  FileManager *FileManager::Instance() {
    if(_instance != NULL) {
      return(_instance);
    } else {
      _instance = new FileManager();
    }
  }

  // other operations...

END

START main.cpp

  void main() {
    char *szFileToShred = "Credit Card Numbers.txt";
    FileManager *fm;

    fm = FileManager::Instance();
    fm->ShredFile(szFileToShred);
  }

END

Of course this example is simplistic, but it illustrates the principles. In most modern medium to large scale software projects, the number of objects can grow quite large, and tracking the existence or non-existence of objects to control resources can be greatly simplified by a singleton object.

A singleton is a good substitute for an object that would be global in a throw away or utility project. It has the added advantage of being able to logically decide if it should return an existing object, a new object or no object at all based on how the Instanciate() function is written.