What is singleton design pattern



What is singleton design pattern..

Answer / 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

More Design Patterns Interview Questions

Is singleton scope thread safe?

0 Answers  


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

0 Answers  


What are 5 common problems in the software development process?

1 Answers   HP,


What are the benefits of the proxy in the design pattern?

0 Answers  


What is Architecture and what is design? Are they related?

3 Answers   Accenture, IBM,






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

0 Answers  


What is the gang of four design pattern?

0 Answers  


Explain the singleton, facade, or handle class design pattern?

2 Answers   ABC,


what is cascading order?

1 Answers  


What is the builder pattern?

0 Answers  


What is the factory pattern in the design pattern?

0 Answers  


What is a behavioral design pattern?

0 Answers  


Categories