The reason I am not creating a
static
object is because I need to have the ability to delete the created concrete object.I have a base and derived class since I need to have different kinds of concrete classes.
I cannot use the
getInstance()
function in the base class since I cannot make it both static and virtual.
class ITrafficEventsReturner {
public: virtual ~ITrafficEventsReturner() {} ;
protected:
ITrafficEventsReturner() { };
// no definition for copy constructor and assignment operator
ITrafficEventsReturner(const ITrafficEventsReturner&);
ITrafficEventsReturner& operator=(const ITrafficEventsReturner&); };
class ConcreteTrafficReturner : public ITrafficEventsReturner {
public:
static ConcreteTrafficReturner* getInstance() {
if (myself == 0)
{
myself = new ConcreteTrafficReturner();
}
return myself; }
~ConcreteTrafficReturner()
{
if (myself)
{
delete myself;
myself = 0;
}
}
private : ConcreteTrafficReturner() : ITrafficEventsReturner() {
};
static ConcreteTrafficReturner* myself; };
ConcreteTrafficReturner* ConcreteTrafficReturner::myself = 0;
int main()
{
ITrafficEventsReturner* ConcreteTrafficReturner =
ConcreteTrafficReturner::getInstance();
delete ConcreteTrafficReturner;
};
This seems to be the possible solution :
class SingletonInterface
{
public:
template <class T>
static T& getInstance()
{
return T::getInstance();
}
private:
SingletonInterface() { };
};
class TrafficGenerator
{
public:
static TrafficGenerator& getInstance()
{
static TrafficGenerator obj;
return obj;
}
void whatAmI()
{
std::cout << " I am Traffic Generator" << std::endl;
}
private:
TrafficGenerator () {};
};
int main()
{
TrafficGenerator& hTG = SingletonInterface::getInstance<TrafficGenerator>() ;
hTG.whatAmI();
};