Hello,
So basically, I am trying to create a system based on the Singleton Pattern and I'm confused.
If I have an Animal class, as well as a Cat class which is derived from Animal and then using a Singleton class will create a single object of which-ever class has been selected (dog, horse, cat etc..):
Animal.h
class Animal {
public:
virtual int age() = 0;
virtual void breed() = 0;
};
Cat.h
#include "Animal.h"
class Cat : public Animal {
public:
Cat();
int age();
void breed();
};
Cat.cpp
Cat::Cat(){};
int Cat::age()
{
return 10;
}
void Cat::breed()
{
}
Singleton.h
#include "Animal.h"
#include <iostream>
using namespace std;
class Singleton
{
private:
static bool instanceFlag;
static Singleton *single;
Singleton()
{
}
public:
static Singleton* getInstance();
Animal *method(string something);
~Singleton()
{
instanceFlag = false;
}
};
Singleton.cpp
#include "Singleton.h"
#include <iostream>
using namespace std;
bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
{
if(!instanceFlag)
{
single = new Singleton();
instanceFlag = true;
return single;
}else{
return single;
}
}
Animal *Singleton::method(string something)
{
if(something == "cat")
{
// new Cat instance
}
// etc
}
main.cpp
#include <iostream>
#include "Singleton.h"
using namespace std;
int main()
{
Singleton *sc1;
sc1 = Singleton::getInstance();
sc1->method("Cat");
return 0;
}
Anyone know where I am going wrong? Why I can't create a new Cat and call it's methods...?
Any help would be amazing :)!