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
What are useful tools for developing and testing color schemes for web sites?
What are the SDLC phases you have invloved ?
What is meant by design 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 strategy design pattern?
When should design patterns be used?
What are the disadvantages of singleton pattern?
Suppose we have file(ps), dont know how many records are there. Move half of the records to 2 files. How can we do?
When singleton pattern is used?
What are the types of participants of the prototype design pattern you will get?
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 builder and composite?
Did you use ooa/ood methodologies? Did you use design patterns?
What is the creational design pattern?
What is the difference between architecture and design?