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
Why have we declared the instance reference volatile?
Explain what is good design?
What are creational design patterns?
Why singleton beans are not thread safe?
Give me example of observer design pattern?
Which design patterns have you used in your project ?
What is the difference between factory and strategy design pattern?
What are the main usage of the patterns?
What are the categories in which the design patterns can be divided?
What is the concurrency design pattern?
What is proxy in design pattern?
5.Develop an entity relationships diagram that identifies physical entity relationships.
What are the languages used in the design pattern?
How do you choose a design pattern?
Is singleton an anti pattern?