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


Please Help Members By Posting Answers For Below Questions

Which design pattern is mostly used in net?

784


What is aop design?

747


Why have we declared the instance reference volatile?

741


4. Identify and bound the SOI’s Operating Environment.

3528


What are the additional productivity features and enhancements included with Quartus II software version 6.0?

2120


What is the singleton design pattern?

800


What is factory method in design pattern?

758


What is singleton design pattern in java?

817


What is the use of repository pattern?

769


What are the most popular design patterns?

773


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

740


Using any system, product, or service your organization provides, identify the human system roles for the product.

2351


What are the most important software design patterns?

824


Suppose we have file(ps), dont know how many records are there. Move half of the records to 2 files. How can we do?

778


Contact a system development program in your organization. Research how they analyzed their SYSTEM OF INTEREST (SOI), its OPERATING ENVIRONMENT, and their respective system elements. How was this analysis reflected in the SOI architecture?

3815