Singleton Pattern

By Frank Losasso

Purpose of the visitor pattern

Ensure a class only has one instance, and provide a global point of access to it. By including the .h file, any portion of the program will be able to access the instance and invoke it’s methods.

Motivation

Many classes should only have one instance, and be accessible from anywhere (many utilities, controllers, viewers etc. follow this pattern), this is where the singleton pattern excels. It will allow for global access of the same instance, and the private constructor prevents multiple instances from being created.

Applicability

Use the Singleton pattern when

next: ParticipantsStructure

Consequences

The Singleton pattern has several benefits:

  1. Controlled access to sole instance. Because the Singleton class encapsulates its sole instance, it can have strict control over how and when clients access it.
  2. Reduced name space. The Singleton pattern is an improvement over global variables. It avoids polluting the name space with global variables that store sole instances.
  3. Permits refinement of operations and representation. The Singleton class may be subclassed, and it's easy to configure an application with an instance of this extended class. You can configure the application with an instance of the class you need at run-time.
  4. Permits a variable number of instances. The pattern makes it easy to change your mind and allow more than one instance of the Singleton class. Moreover, you can use the same approach to control the number of instances that the application uses. Only the operation that grants access to the Singleton instance needs to change.
  5. More flexible than class operations. Another way to package a singleton's functionality is to use class operations (that is, static member functions in C++ or class methods in Smalltalk). But both of these language techniques make it hard to change a design to allow more than one instance of a class. Moreover, static member functions in C++ are never virtual, so subclasses can't override them polymorphically.

 

 

Sample code:

 

In .h file

 

private:

// Pointer to this class (singleton)

      static Timer*     singletonInstance;

 

      /**

       * constructor

       */

      Timer             ();

public:

 

      /**

       * function which accessed the singleton

       */

      static inline Timer* singleton            ()

      {

            if (singletonInstance == 0)  // is it the first call?

            { 

                  singletonInstance = new Timer(); // create sole instance

            }

            return singletonInstance; // address of sole instance

      }

 

 

In .cpp file

Timer* Timer::singletonInstance = 0;// initialize pointer

 

 

 

Material taken from the Design Patterns CD