a class has only one instance, and provide a global point of
access to it.
initialization on
first use only
//mysingletone.C
#include<iostream>
using namespace std;
class singletone {
singletone () {} //Constructor made Private
singletone(const singletone &); //Copy Constructor Hidden and Not Implemented
public:
void display();
static singletone &getstring() //returns class object singletone
{
static singletone singObj;
return singObj;
}
};
void singletone::display() //becomes singletone.display();
{
cout << "Welcome to Karwar" << endl;
return;
}
int main()
{
cout << "singleton code" << endl;
singletone::getstring().display();
return 0;
}
Result:
singleton code Welcome to Karwar
//Singleton Design pattern using reference variable
//singletonwithpointer.C
#include<iostream>
using namespace std;
class singletonRef {
static singletonRef *singleObj;
singletonRef() {}
singletonRef(const singletonRef &);
public:
void display ();
static singletonRef &getstring ()
{
if( singleObj == 0)
singleObj = new singletonRef();
return *singleObj;
}
};
singletonRef *singletonRef::singleObj = 0;
void singletonRef::display ()
{
cout << "Welcome To Karwar" << endl;
}
int main ()
{
cout << "singleton using pointer" << endl;
singletonRef::getstring().display ();
return 0;
}
Result:
singleton using pointerWelcome to Karwar
//singleton design pattern using Pointer
//singleusingpointer.C#include<iostream>
using namespace std;
class singletonRef {
static singletonRef *singleObj;
singletonRef() {}
singletonRef(const singletonRef &);
public:
void display ();
static singletonRef *getstring ()
{
if( singleObj == 0)
singleObj = new singletonRef();
return singleObj;
}
};
singletonRef *singletonRef::singleObj = 0;
void singletonRef::display ()
{
cout << "Welcome to Karwar" << endl;
}
int main ()
{
cout << "singleton using pointer" << endl;
singletonRef::getstring()->display ();
return 0;
}
Result:
singleton using pointerWelcome to Karwar