It can be found in many advices on topic that having Singletons is an anti-pattern. Especially for cases of testability. Can someone please advice/critique on this way (please see code below) of dealing with this kind issue.
Also please kindly confirm/correct that the presented way of passing a reference to ISingleton in SingletonUser ctor reflects notion of what is called dependancy injection.
#include <iostream>
class ISingleton
{
public:
virtual void doOp() = 0;
virtual ~ISingleton() = default;
};
class Singleton : public ISingleton
{
public:
static Singleton& get()
{
static Singleton s;
return s;
}
void doOp() override
{
get().doOpImpl();
}
private:
void doOpImpl()
{
std::cerr << "Singleton: " << __func__ << '\n';
}
private:
Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton& operator=(Singleton&&) = delete;
};
class SingletonUser
{
public:
SingletonUser(ISingleton& i = Singleton::get()) : i_{i}
{}
void operator()()
{
i_.doOp();
}
private:
ISingleton& i_;
};
class SingletonMock : public ISingleton
{
public:
void doOp() override
{
std::cerr << "SingletonMock: " << __func__ << '\n';
}
};
int main()
{
SingletonUser su;
su();
SingletonMock sm;
SingletonUser s_user_mocked{sm};
s_user_mocked();
}