Recently I got question on implement Singleton but abstract base class involved. Suppose we have class hierarchy like this:
class IFoo {...}; // it's ABC
class Foo : public IFoo {...};
we have singleton class defined as follows:
template <typename T>
class Singleton
{
public:
static T* Instance() {
if (m_instance == NULL) {
m_instance = new T();
}
return m_instance;
}
private:
static T* m_instance;
};
So if I want to use like following: IFoo::Instance()->foo();
what should I do?
If I do this: class IFoo : public Singleton<IFoo> {...};
it won't work since Singleton will call IFoo's ctor but IFoo is a ABC so can not be created.
And this: class Foo : public IFoo, public Singleton<Foo> {...};
can't work too, because this way class IFoo doesn't have the interface for method Instance(), so the call IFoo::Instance()
will fail.
Any ideas?