It is well known that Singletons are anti-patters for several reasons:
- tight coupling
- singletons are pathological liars
- no testability
- inheritance is not available
- you cannot program to interfaces, you program to implementations
But there is the code:
class ISingleton
{
protected:
ISingleton() {}
public:
virtual ISingleton& getInstance() = 0;
virtual void doSomething() = 0;
virtual ~ISingleton(){}
};
class SingletonA : public ISingleton
{
public:
virtual SingletonA& getInstance() override
{
static SingletonA instance;
return instance;
}
virtual void doSomething() override
{
}
};
class SingletonB : public ISingleton
{
public:
virtual SingletonB& getInstance() override
{
static SingletonB instance;
return instance;
}
virtual void doSomething() override
{
}
};
class DependsOnSingleton
{
private:
ISingleton& m_singleton;
public:
DependsOnSingleton(ISingleton& singleton)
: m_singleton {singleton}
{
}
void use()
{
m_singleton.doSomething();
}
};
Do you see any of the problems in the code listed above? And it completely assures that a single instance can be created. You can see here direct dependency injection is used, it could also be used with DI containers too. I think people just misunderstand what Singleton is for. Do I miss something?