+ Reply to Thread
Results 1 to 2 of 2

Thread: What is Singleton design pattern? Please provide example in C++?

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    49

    What is Singleton design pattern? Please provide example in C++?

    What is Singleton design pattern? Please provide example in C++?

  2. #2
    Singleton design pattern is used to create single object of a class and used it for the complete life-time of application.

    Example:

    Code:
    class CSingleton
    {
    private:
    	CSingleton()
    	{
    		m_nValue = 0 ;
    	}
    
    	int m_nValue ;
    public:
    	
    	static CSingleton* GetSingletonObject()
    	{
    		//remember that this is going to assign only once for the first call of GetSingletonObject() method
    		//for the rest of the call same pointer is going to return.
    		static CSingleton* pSingleton = new CSingleton() ;
    
    		return pSingleton ;
    	}
    
    	int GetValue()
    	{
    		return m_nValue ;
    	}
    } ;
    
    void UsingSingleton()
    {
    	CSingleton *pSingleton = CSingleton::GetSingletonObject() ;
    	int nValue  = pSingleton->GetValue() ;
    
    	pSingleton = CSingleton::GetSingletonObject() ;
    	nValue  = pSingleton->GetValue() ;
    }

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts