Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C++
Article

Singleton Pattern & its implementation with C++

Rate me:
Please Sign up or sign in to vote.
4.40/5 (47 votes)
4 Mar 20022 min read 719.7K   78   41
Singleton is one of the commonly used patterns in object oriented developments. In this article I am discussing abt this pattern in general and how we can implement this pattern with C++.

Introduction

Suppose we have to use a single object of a class throughout the lifetime of an application. In C++, it is possible to declare a global object, which can be used anywhere inside the program. But a good object oriented design strictly prohibits the use of global variables or methods, since they are against the fundamental principles of object orientation like data encapsulation or data hiding. More over, most latest object oriented programming languages like JAVA or C# do not support global variables or functions.

Another practical solution to get a single object is by declaring a class, which contains only static methods. A static class is loaded into memory when the execution of the program starts and it remains there till the application ends. Remember that for invoking a static method of a class, it is not necessary to create an instance of the class. But remember that a class with only static methods and variables are not a good object oriented design. A class of static methods unfortunately breaks down to a list of functions or utilities.

When we want to create only one instance of a class in a truly object oriented fashion by adhering to the basic principles of object oriented programming, the Singleton patterns are used. The Singleton Pattern comes under that classification of Creational Pattern, which deals with the best ways to create objects. The Singleton Design pattern is used, where only one instance of an object is needed throughout the lifetime of an application. The Singleton class is instantiated at the time of first access and same instance is used thereafter till the application quits.

There are very good non-software examples available in real world for Singleton patterns. The office of the Principal of my college is a Singleton. The University specifies the means by which a principal is selected, limits the term of office, and defines the order of succession. As a result, there can be at most one active principal at any given time. Regardless of the personal identity of the principal, the title, "The Principal" is a global point of access that identifies the person in the office.

The Singletons are often used to control access to resources such as database connections or sockets. Suppose we have a license for only one connection for our database. A Singleton connection object makes sure that only one connection can be made at any time.

It is pretty easy to implement the Singleton Pattern in any object oriented programming languages like C++, JAVA or C#. There are lots of different ways to implement the Singleton Pattern. But by using a private constructor and a static method to create and return an instance of the class is a popular way for implementing Singleton Pattern. The UML representation of a Singleton Pattern is shown below.

Image 1

C++ Implementation

/*
Creational Pattern: SINGLETON
Author: Rajesh V.S
Language: C++
Email: rajeshvs@msn.com
*/

#include <iostream>

using namespace std;

class Singleton
{
private:
    static bool instanceFlag;
    static Singleton *single;
    Singleton()
    {
        //private constructor
    }
public:
    static Singleton* getInstance();
    void method();
    ~Singleton()
    {
        instanceFlag = false;
    }
};

bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
{
    if(! instanceFlag)
    {
        single = new Singleton();
        instanceFlag = true;
        return single;
    }
    else
    {
        return single;
    }
}

void Singleton::method()
{
    cout << "Method of the singleton class" << endl;
}

int main()
{
    Singleton *sc1,*sc2;
    sc1 = Singleton::getInstance();
    sc1->method();
    sc2 = Singleton::getInstance();
    sc2->method();

    return 0;
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionIs this implementation correct? Pin
Member 128842562-Dec-16 20:30
Member 128842562-Dec-16 20:30 
QuestionSingleton class Pin
ranjithkumar8118-Oct-13 20:31
ranjithkumar8118-Oct-13 20:31 
GeneralMy vote of 1 Pin
NSProgrammer4-Sep-13 18:27
NSProgrammer4-Sep-13 18:27 
QuestionWhat if I init this way Pin
Balkrishna Talele19-Feb-13 22:19
Balkrishna Talele19-Feb-13 22:19 
AnswerRe: What if I init this way Pin
Abdallah Al-Dalleh31-Mar-14 23:04
Abdallah Al-Dalleh31-Mar-14 23:04 
AnswerRe: What if I init this way Pin
Abhijeet Pathak3-Mar-16 0:11
Abhijeet Pathak3-Mar-16 0:11 
GeneralRegarding Singleton class object creation Pin
Member 884300724-Jul-12 2:18
Member 884300724-Jul-12 2:18 
QuestionCould it be more easy? Pin
DmitrijNik18-Feb-12 3:06
DmitrijNik18-Feb-12 3:06 
QuestionRe: memory leak Pin
Michael B Pliam14-Dec-11 8:52
Michael B Pliam14-Dec-11 8:52 
I think it's pretty good. Certainly simple and straightforward.

Because the class recognizes whether or not a class pointer is NULL or not, you cannot delete the class pointer after each use because when you call the class getInstance again, a new instance will be instantiated and the class will no longer function as a Singleton. So simply delete the class pointer once, after you're done using it.

Singleton *sc1,*sc2, *sc3, *sc4, *sc5;
sc1 = NULL; sc2 = NULL; sc3 = NULL; sc4 = NULL; sc5 = NULL;
sc1 = Singleton::getInstance(); sc1->method(); //delete sc1; sc1 = NULL;
sc2 = Singleton::getInstance(); sc2->method(); //delete sc2; sc2 = NULL;
sc3 = Singleton::getInstance(); sc3->method(); //delete sc3; sc3 = NULL;
sc4 = Singleton::getInstance(); sc4->method(); //delete sc4; sc4 = NULL;
sc5 = Singleton::getInstance(); sc5->method(); delete sc5; sc5 = NULL;

No leak!! Only one instance constructed.

Not sure about how to make it thread safe. Any ideas how to add a critical section ? Smile | :)
GeneralMy vote of 3 Pin
Konobey19-Jul-11 12:36
Konobey19-Jul-11 12:36 
GeneralMy vote of 5 Pin
aurerilo14-Jul-11 4:33
aurerilo14-Jul-11 4:33 
GeneralMy vote of 1 Pin
Giri Ganji16-Sep-10 20:13
Giri Ganji16-Sep-10 20:13 
GeneralCould be better... Pin
Bogdan Mustiata9-Jun-06 7:50
Bogdan Mustiata9-Jun-06 7:50 
Questionwhat if ... Pin
Tom Utal2-Sep-04 3:15
Tom Utal2-Sep-04 3:15 
AnswerRe: what if ... Pin
vish11112-Aug-08 22:51
vish11112-Aug-08 22:51 
Questionsimpler code? Pin
Alex Chirokov14-Jul-04 2:16
Alex Chirokov14-Jul-04 2:16 
AnswerRe: simpler code? Pin
RNEELY29-Sep-04 4:10
RNEELY29-Sep-04 4:10 
GeneralRe: simpler code? Pin
Alex Chirokov29-Sep-04 8:10
Alex Chirokov29-Sep-04 8:10 
GeneralRe: simpler code? Pin
vish11112-Aug-08 22:53
vish11112-Aug-08 22:53 
GeneralRe: simpler code? Pin
vasu_sri1-Apr-12 23:50
vasu_sri1-Apr-12 23:50 
QuestionIs it really a singleton? Pin
ThumbUp25-Apr-04 23:22
ThumbUp25-Apr-04 23:22 
AnswerRe: Is it really a singleton? Pin
Bogdan Mustiata9-Jun-06 22:04
Bogdan Mustiata9-Jun-06 22:04 
AnswerRe: Is it really a singleton? Pin
vish11112-Aug-08 22:55
vish11112-Aug-08 22:55 
AnswerRe: Is it really a singleton? Pin
Member 1211239726-Apr-16 22:03
Member 1211239726-Apr-16 22:03 
GeneralAlternative Thread Safe Singleton Pin
Paul Evans8-Dec-02 1:34
Paul Evans8-Dec-02 1:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.