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

What are creational design patterns?

0 Answers  


Identify three types of systems or system upgrades that may be ideal candidates for a Waterfall Development Model strategy.

1 Answers  


2. Create your own de&#64257;nition of a system. Based on the “system” de&#64257;nitions a. Identify your viewpoint of shortcomings in the de&#64257;nitions. b. Provide rationale as to why you believe that your de&#64257;nition overcomes those shortcomings. c. From an historical perspective, identify three precedented systems that were replaced by unprecedented systems.

0 Answers   IBM,


Can we have this pattern implemented using static class?

0 Answers  


SAP Design Studio live classes by Exports

1 Answers   SAP Labs,


. How can a product be accessible to differently-abled people?

3 Answers  


Describe the builder design pattern

0 Answers  


Is dependency injection a design pattern?

0 Answers  


What are sequence diagrams, collaboration diagrams and difference between them ?

8 Answers   ACET, CT, CTS, Infosys,


What is difference between GoF and J2EE patterns?

1 Answers   Accenture,


Is singleton a design pattern?

0 Answers  


How to test the quality of design ?

1 Answers  


Categories