Click here to Skip to main content
Licence CPOL
First Posted 9 Feb 2012
Views 3,890
Downloads 67
Bookmarked 6 times

Understanding & Implementing Singleton Pattern in C++ and C#

By | 9 Feb 2012 | Article
Understanding and Implementing Singleton Pattern in C++ and C#

Introduction

This article presents a basic explanation of when we need a singleton pattern, what is singleton pattern and how to implement it in C++ and C#.

Background

The first thing is when do we need singleton patterns. If we have a system that requires:

  • A single instance is required on a subsystem and the subsystem itself is able to enforce the single instance on itself and the rest of the system need not have to worry about it.
  • This single instance subsystem should be accessible by the complete system or say by most part of the system. We can say globally accessible too.
  • This single instance subsystem should not be created and initialized unless it is required. (We know it as lazy initialization.)

Now these are the three good reasons that any good or bad book refers to as the scenarios when we should use singleton pattern but I will say, even if you have the first requirement then use this pattern.

OK now let us look at that subsystem that requires a single instance and make it a single class, assuming that this subsystem provides unique services to the system. If not, then the first good idea will be to try to break this subsystem into further parts so that all the parts can be packed inside a single classes.

We are saying that the class should provide one and only one instance, so how can that be achieved because any application wanting to create an instance of this class calls its constructor but wait hey constructor so why not restrict the applications from freely accessing the constructor. So the first thing we need to do is to make the constructor private.

We going to create that one instance that is required. OK, for that, let's write some method for this class, say Getinstance which can actually create an object of this class and give it to the applications. Now since we want to use this method on this class to create the objects, we have to make it static.

Good so now we have our singleton class in place and we are happy that we have successfully created a singleton class. And for a C# guy, this assumption is actually true but for a C++ guy, do we really have a singleton class ready. Well the way I see this class has a problem and on the top of the list is that it is not at all singleton.

The reason I am saying this class is not singleton is what of an application does this:

Singleton s(Singleton::Getinstance());

and the default copy semantics in C++ will let the user create many objects of this type so what we need to do next is to prevent the copy operations.

Now we can say we have a fairly good singleton class. This class now shows a perfect example, rudimentary though, of how to create a simple singleton class.

Using the Code

Here is the C++ implementation of the Singleton class:

class Singleton
{
private:
    Singleton(void)
    {
        //Do the resource allocation here, perhaps opening a log file
    }

    //Lets prevent copy operations for this class
    Singleton(const Singleton&);
    Singleton& operator=(const Singleton&);    

public:
    ~Singleton(void)
    {
        //release the resource here, perhaps closing the log file
    }

    static Singleton& Getinstance()    
    {            
        //We need to use a scoped_lock here to ensure thread safety

        //Local static variable, This way we can ensure lazy initialization 
        static Singleton instance;
        return instance;
    }    

    void LogMessage(std::string msg)
    {
        //Perhaps log the message in some file or event viewer
        std::cout << msg << "\n"; //cout for testing
    }
};

Here is the C# implementation of the Singleton class:

sealed class Singleton
{
    private Singleton()
    {
        //Do the resource allocation here, perhaps opening a log file
    }

    private static Singleton instance = null;

    //introduced to facilitate thread safety
    private static readonly object myLock = new Object();

    ~Singleton()
    {
        //release the resource here, perhaps closing the log file
    }

    public static Singleton GetInstance()
    {
        //This has been introduced to make it thread safe and 
        //keep the lazy initialization as is.
        lock (myLock)
        {
            if (instance == null)
            {
                instance = new Singleton();
            }

            return instance;
        }
    }

    public void LogMessage(string msg)
    {
        //Perhaps log the message in some file or event viewer
        Console.WriteLine(msg); //console for testing
    }
}

Note: Please refer to the source code for implementation details and test code.

Points of Interest

Although this stuff is very basic and the way I implemented it portrays it like a very small activity, it could really be useful for the guys who are just at the start of their career and are looking forward to learning about programming styles and good design.

History

  • 9th February, 2012: Initial version
  • 9th February, 2012: Minor changes to ensure lazy initialization and thread safety.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Rahul Rajat Singh

Software Developer

India India

Member

I am into Software Development since 2005. I have experience in developing Multimedia applications(Audio & Video Playback), Small 3D games using native(C++) and Managed(C#) Languages, Windows Form Applications using C#, Windows Applications using C++/MFC, e-commerce/e-governance Portals, Content Management Systems and Data driven websites.
 
My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems.
 
My skill Set: C/C++, C#, ASP.NET, ADO.NET, JavaScript, SQL Server, Design Patterns

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 1 Pinmemberzennie21:48 19 Mar '12  
GeneralMy vote of 2 PinmemberMember_Rose23:14 12 Feb '12  
GeneralMy vote of 1 PinmemberNebojsa Janjic20:55 9 Feb '12  
GeneralMy vote of 1 PinmemberJohn Brett5:55 9 Feb '12  
GeneralMy vote of 1 PinmemberSledgeHammer015:06 9 Feb '12  
GeneralMy vote of 1 PinmemberFardan5:02 9 Feb '12  
QuestionNot thread-safe. PinmvpPaulo Zemek3:54 9 Feb '12  
AnswerRe: Not thread-safe. PinmemberFardan5:00 9 Feb '12  
QuestionToo many singletons PinmemberJonathan [Darka]3:27 9 Feb '12  
Questionjon skeet has an excellant discussion of this for C# Pinmemberxoox3:20 9 Feb '12  

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

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 9 Feb 2012
Article Copyright 2012 by Rahul Rajat Singh
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid