// Implement the Doubleton pattern with a twist.First, instead of storing one instance,
// store two instances.And in every even call of getInstance(), return the first instance
// and in every odd call of getInstance(), return the second instance.
#include <iostream>
#include <string>
using namespace std;
class Doubleton {
public:
static Doubleton* Instance();
void printInstanceNum()
{
cout << instNum << endl;
};
private:
Doubleton() {}; // Private so that it can not be called
Doubleton(Doubleton const&) {}; // copy constructor is private
Doubleton& operator=(Doubleton const&) {}; // assignment operator is private
static Doubleton* m_pInstance1;
static Doubleton* m_pInstance2;
bool returnInstance1;
int instNum;
};
// Global static pointers used to ensure only 2 instances
Doubleton* Doubleton::m_pInstance1 = NULL;
Doubleton* Doubleton::m_pInstance2 = NULL;
// User must call the Instance function as the constructor
// is private to ensure only a single instance exists
Doubleton* Doubleton::Instance()
{
// Only allow one instance of class to be generated.
if (!m_pInstance1 || !m_pInstance2)
{
m_pInstance1 = new Doubleton;
m_pInstance2 = new Doubleton;
m_pInstance1->instNum = 1;
m_pInstance2->instNum = 2;
}
if (m_pInstance1->returnInstance1)
{
cout << "returning inst 1" << endl;
m_pInstance1->returnInstance1 = false;
m_pInstance2->returnInstance1 = false;
return m_pInstance1;
}
else
{
cout << "returning inst 2" << endl;
m_pInstance1->returnInstance1 = true;
m_pInstance2->returnInstance1 = true;
return m_pInstance2;
}
}
int main()
{
Doubleton* inst1 = Doubleton::Instance();
Doubleton* inst2 = Doubleton::Instance();
inst1->printInstanceNum();
inst2->printInstanceNum();
inst1 = Doubleton::Instance();
inst1->printInstanceNum();
inst1 = Doubleton::Instance();
inst1->printInstanceNum();
return 0;
}
Comentarios