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

Give me example of observer design pattern?

0 Answers  


Is dependency injection a design pattern?

0 Answers  


What is lexi design pattern?

0 Answers  


Why have we used synchronized here?

0 Answers  


What is design pattern ?

4 Answers   Accenture,






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

0 Answers  


Write the code for a singleton class?

0 Answers  


Why is it important to use systems analysis and design methodologies when building a system? Why not just build the system in whatever way appears to be “quick and easy”? What value is provided by using an “engineering” approach?

1 Answers   DBU, KSV College, Sampson, University of Ibadan,


what is the difference between the Adapter Pattern and Proxy Patterns?its seems both are almost similar?

1 Answers   RBS,


Explain what are 5 common problems in the software development process?

0 Answers  


What are the examples of the behavioral design patterns?

0 Answers  


What is the publish/subscribe model?

1 Answers  


Categories