What is singleton design pattern

Answer Posted / lokesh

Singleton design pattern is a a creational pattern to
dictate how and when objects get created and it's main
purpose is to ensure that a class has only one instance

Example:
#define NULL 0

class Singleton
{
private:
Singleton(Singleton&){}
Singleton& operator =(Singleton&);
int nValue;
static Singleton* pSingleton;
Singleton():nValue(10)
{
}
public:
static Singleton*Instance()
{

if(NULL == pSingleton)
{
pSingleton = new Singleton();
}
return pSingleton;
}
void setValue(int val)
{
nValue = val;
}
int getValue()
{
return nValue;
}
};
Singleton* Singleton::pSingleton = NULL;

int main(int argc, char* argv[])
{
Singleton *abc = NULL;
cout<<Singleton::Instance()->getValue()<<endl;
Singleton::Instance()->setValue(20);

Singleton *xyz = NULL;
cout<<xyz->Instance()->getValue()<<endl;
Singleton *sss = Singleton::Instance();
return 0;
}

Is This Answer Correct ?    16 Yes 5 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is synchronizer token pattern?

594


What is the difference between factory and abstract factory design pattern?

570


Explain three types of components comprise an application design?

575


What are the languages used in the design pattern?

566


What is single tone design pattern in java?

540






What is the difference between builder and composite?

604


What is the design pattern?

632


What is the difference between 3 tier and n tier architecture?

595


Why should we not use singleton pattern?

563


What are the differences between the design patterns and the framework?

593


Using any system, product, or service your organization provides, identify the human system roles for the product.

2176


Did you use ooa/ood methodologies? Did you use design patterns?

632


What is viper architecture?

602


What are the SDLC phases you have invloved ?

2170


Which design patterns have you used in your project ?

561