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
Quartus II software version 6.0 is available for which operating systems (OS)?
Did you use ooa/ood methodologies? Did you use design patterns?
How did you design your unit tests?What about integration tests?
Why have we declared the instance reference volatile?
Why singleton beans are not thread safe?
What is the use of repository pattern?
when performing a functional test on a phone calculator,if pressing on a button does not function what do i do next
What is the difference between factory and builder design pattern?
Shall we use abstract classes or interfaces in policy / strategy design pattern?
Hi, I have 9backlogs in btech and i am 2008 passed out,am working with an MNC from past 3 years.now, am willing to do MS, will it be any problem for me?
What is the difference between adapter and facade?
What are the SDLC phases you have invloved ?
What are the examples of the behavioral design patterns?
What is the prototype design pattern?
Explain what are 5 common problems in the software development process?