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

Are you using singleton in your code?

595


Can we have this pattern implemented using static class?

581


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

602


What is onion architecture?

644


Give me example of observer design pattern?

634






Why is singleton bad?

577


What are the 23 design patterns?

722


How did you design your unit tests?What about integration tests?

1805


What is a behavioral design pattern?

629


What is factory method in design pattern?

569


What are creational design patterns?

636


What is lexi design pattern?

716


What is the singleton design pattern?

633


What is the difference between factory and builder design pattern?

509


Why is singleton used?

631