Click here to Skip to main content
6,631,889 members and growing! (18,388 online)
Email Password   helpLost your password?
Languages » C / C++ Language » General     Advanced

Singleton Pattern & its implementation with C++

By vsrajeshvs

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++.
C++, Windows, Visual Studio, Dev
Posted:4 Mar 2002
Views:173,913
Bookmarked:44 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
26 votes for this article.
Popularity: 4.99 Rating: 3.53 out of 5
4 votes, 19.0%
1
3 votes, 14.3%
2
3 votes, 14.3%
3
7 votes, 33.3%
4
4 votes, 19.0%
5

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.

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

About the Author

vsrajeshvs


Member

Location: United States United States

Other popular C / C++ Language articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 27 (Total in Forum: 27) (Refresh)FirstPrevNext
GeneralCould be better... PinmemberBogdan Mustiata8:50 9 Jun '06  
Generalwhat if ... PinmemberTom Utal4:15 2 Sep '04  
GeneralRe: what if ... Pinmembervish11123:51 12 Aug '08  
Generalsimpler code? PinmemberAlex Chirokov3:16 14 Jul '04  
GeneralRe: simpler code? PinmemberRNEELY5:10 29 Sep '04  
GeneralRe: simpler code? PinmemberAlex Chirokov9:10 29 Sep '04  
GeneralRe: simpler code? Pinmembervish11123:53 12 Aug '08  
GeneralIs it really a singleton? PinmemberThumbUp0:22 26 Apr '04  
GeneralRe: Is it really a singleton? PinmemberBogdan Mustiata23:04 9 Jun '06  
GeneralRe: Is it really a singleton? Pinmembervish11123:55 12 Aug '08  
GeneralAlternative Thread Safe Singleton PinmemberPaul Evans2:34 8 Dec '02  
GeneralMemory leak ? PinsussGizMoCuz12:31 9 Jul '02  
GeneralRe: Memory leak ? Pinmemberjan larsen3:51 25 Jul '02  
GeneralRe: Memory leak ? PinsussChris Stoy5:04 7 Oct '02  
GeneralRe: Memory leak ? Pinmemberjan larsen5:57 7 Oct '02  
GeneralRe: Memory leak ? PinmemberPaul Evans2:40 8 Dec '02  
GeneralRe: Memory leak ? PinsussAnonymous13:33 10 Jul '03  
GeneralRe: Memory leak ? PinmemberPuponacid8:52 8 Sep '04  
GeneralRe: Memory leak ? Pinmemberjan larsen20:39 8 Sep '04  
GeneralRe: Memory leak ? PinmemberPuponacid2:09 10 Sep '04  
GeneralRe: Memory leak ? PinsussAnonymous10:26 10 May '05  
GeneralRe: Memory leak ? Pinmemberjan larsen22:40 10 May '05  
GeneralRe: Memory leak ? PinmemberKontaxis11:29 25 Jun '08  
GeneralRe: Memory leak ? Pinmemberjan larsen4:29 26 Jun '08  
GeneralNice, but... PinmemberNish - Native CPian23:36 16 Jun '02  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 4 Mar 2002
Editor: Nishant Sivakumar
Copyright 2002 by vsrajeshvs
Everything else Copyright © CodeProject, 1999-2009
Web21 | Advertise on the Code Project